0%

[題解]無刻度容器倒水問題

a142. 無刻度容器倒水問題

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <bits/stdc++.h>
#define ll long long
#define double long double
#define N 2000
#define Orz ios::sync_with_stdio(0),cin.tie(0)
#define INF 2e18
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define rrep(i,l,r) for(int i=l;i<r;i++)
#define pii pair<int,int>
#define x first
#define y second
using namespace std;
int x,y,z;
int a[N][N];bool visit[N][N];

void solve(){
cin>>x>>y>>z;
memset(a,0x3f3f3f3f,sizeof(a));memset(visit,0,sizeof(visit));
a[0][0] = 0;
queue<pii>que;
que.push({0,0});
visit[0][0] = 1;

bool f = 0;
while(!que.empty()){
pii cur = que.front();
que.pop();
int mmin = cur.x,mmax = cur.y;
int dx[6] = {max(0,mmax-(y-mmin)),min(mmax+mmin,x),x,mmin,0,mmin};
int dy[6] = {min(y,mmax+mmin),max(0,mmax-(x-mmin)),mmax,y,mmax,0};

for(int i=0;i<6;i++){
int nx = dx[i],ny = dy[i];
if(nx==z||ny==z){
f = 1;
cout<<a[mmin][mmax]+1<<endl;
return;
}
if(visit[nx][ny])continue;
a[nx][ny] = a[mmin][mmax]+1;
visit[nx][ny] = 1;
que.push({nx,ny});
}
}
if(!f)cout<<-1<<endl;
}

signed main(){
Orz;
int t;cin>>t;
while(t--){
solve();
}
}