KunKun的征途

明天的明天,你还会送我水晶之恋吗?

导航

[ZOJ 1005] Jugs (dfs倒水问题)

Posted on 2014-11-12 11:13  西域小车  阅读(375)  评论(0)    收藏  举报

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5

题目大意:给你6种操作,3个数a,b,n,代表我有两个杯子,第一个杯子的容量是a,第二个杯子容量是b,问能否通过6种操作,使得第二个杯子里装水量为n

 

dfs搜搜搜!!

状态dfs(x,y) 代表第一个杯子里有水量x,第二个杯子里有水量y。

代码:

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <string>
 4 #include <iostream>
 5 #include <cstring>
 6 #include <algorithm>
 7 #include <cctype>
 8 #include <vector>
 9 #include <map>
10 #include <set>
11 #include <iterator>
12 #include <functional>
13 #include <cmath>
14 #include <numeric>
15 using namespace std;
16 typedef long long LL;
17 typedef pair<int,int> PII;
18 typedef vector<int> VI;
19 #define PB push_back
20 #define MP make_pair
21 #define SZ size()
22 #define CL clear()
23 #define AA first
24 #define BB second
25 #define EPS 1e-8
26 #define ZERO(x) memset((x),0,sizeof(x))
27 const int INF = ~0U>>1;
28 const double PI = acos(-1.0);
29 
30 int a,b,n;
31 bool vis[1010][1010];
32 VI ans;
33 bool flag;
34 
35 void dfs(int x,int y){
36 //    printf("[dfs]:x=%d,y=%d\n",x,y);
37     if( x<0||y<0 ) return;
38     if( x>a||y>b ) return;
39     if( flag ) return;
40     if( vis[x][y] ) return;
41     vis[x][y] = true;
42     if( y==n ){
43         for(int i=0;i<ans.SZ;i++){
44             if( ans[i]==1 ) puts("fill A");
45             else if( ans[i]==2 ) puts("fill B");
46             else if( ans[i]==3 ) puts("empty A");
47             else if( ans[i]==4 ) puts("empty B");
48             else if( ans[i]==5 ) puts("pour A B");
49             else if( ans[i]==6 ) puts("pour B A");
50         }
51         puts("success");
52         flag = true;
53         return;
54     }
55     for(int i=1;i<=6;i++){
56         ans.PB(i);
57         if( i==1 ) dfs(a,y);
58         else if( i==2 ) dfs(x,b);
59         else if( i==3 ) dfs(0,y);
60         else if( i==4 ) dfs(x,0);
61         else if( i==5 ){
62             int rb = b - y;
63             int pa = min(rb,x);
64             dfs(x-pa,y+pa);
65         }
66         else if( i==6 ){
67             int ra = a - x;
68             int pb = min(ra,y);
69             dfs(x+pb,y-pb);
70         }
71         ans.pop_back();
72     }
73     vis[x][y] = false;
74 }
75 
76 int main(){
77     while(scanf("%d%d%d",&a,&b,&n)!=EOF){
78         ZERO(vis);
79         flag = false;
80         dfs(0,0);
81     }
82     return 0;
83 }