题目链接:http://poj.org/problem?id=3414
思路:bfs简单应用,增对瓶A或者瓶B进行分析就可以了,一共6种状态。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 using namespace std; 7 8 struct Node{ 9 int a,b,step; 10 char str[111][111]; 11 }; 12 13 int A,B,C; 14 bool mark[111][111]; 15 bool bfs() 16 { 17 memset(mark,false,sizeof(mark)); 18 queue<Node>que; 19 Node p,q; 20 p.a=0,p.b=0,p.step=0; 21 que.push(p); 22 mark[0][0]=true; 23 while(!que.empty()){ 24 p=que.front(); 25 que.pop(); 26 if(p.a==C||p.b==C){ 27 printf("%d ",p.step); 28 for(int i=1;i<=p.step;i++){ 29 printf("%s ",p.str[i]); 30 } 31 return true; 32 } 33 if(p.a==0){ 34 q=p; 35 q.a=A; 36 q.step++; 37 strcpy(q.str[q.step],"FILL(1)"); 38 if(!mark[q.a][q.b]){ 39 mark[q.a][q.b]=true; 40 que.push(q); 41 } 42 }else if(p.a<=A){ 43 q=p; 44 q.a=0; 45 q.step++; 46 strcpy(q.str[q.step],"DROP(1)"); 47 if(!mark[q.a][q.b]){ 48 mark[q.a][q.b]=true; 49 que.push(q); 50 } 51 if(p.b<B){ 52 q=p; 53 if(q.a+q.b<=B){ 54 q.b+=q.a; 55 q.a=0; 56 }else { 57 q.a=(q.b+q.a)-B; 58 q.b=B; 59 } 60 q.step++; 61 strcpy(q.str[q.step],"POUR(1,2)"); 62 if(!mark[q.a][q.b]){ 63 mark[q.a][q.b]=true; 64 que.push(q); 65 } 66 } 67 } 68 if(p.b==0){ 69 q=p; 70 q.b=B; 71 q.step++; 72 strcpy(q.str[q.step],"FILL(2)"); 73 if(!mark[q.a][q.b]){ 74 mark[q.a][q.b]=true; 75 que.push(q); 76 } 77 }else if(p.b<=B){ 78 q=p; 79 q.b=0; 80 q.step++; 81 strcpy(q.str[q.step],"DROP(2)"); 82 if(!mark[q.a][q.b]){ 83 mark[q.a][q.b]=true; 84 que.push(q); 85 } 86 if(p.a<A){ 87 q=p; 88 if(q.b+q.a<=A){ 89 q.a+=q.b; 90 q.b=0; 91 }else { 92 q.b=(q.b+q.a)-A; 93 q.a=A; 94 } 95 q.step++; 96 strcpy(q.str[q.step],"POUR(2,1)"); 97 if(!mark[q.a][q.b]){ 98 mark[q.a][q.b]=true; 99 que.push(q); 100 } 101 } 102 } 103 } 104 return false; 105 } 106 107 108 int main() 109 { 110 while(~scanf("%d%d%d",&A,&B,&C)){ 111 if(!bfs())puts("impossible"); 112 } 113 return 0; 114 }