标签:
【题意】有两个水壶,对水壶有三种操作,1)FILL(i),将i水壶的水填满,2)DROP(i),将水壶i中的水全部倒掉,3)POUR(i,j)将水壶i中的水倒到水壶j中,若水壶 j 满了,则 i 剩下的就不倒了,问进行多少步操作,并且怎么操作,输出操作的步骤,两个水壶中的水可以达到C这个水量。如果不可能则输出impossible。初始时两个水壶是空的,没有水。【分析】对于A,B两个瓶子一共会存在6种状态,针对这6种状态分析即可。具体看代码,这题参考了点击打开链接的博客。收获很大。
【AC代码】
#include <set> #include <map> #include <queue> #include <string> #include <vector> #include <cstring> #include <iostream> #include <algorithm> using namespace std; struct node{ int x,y,step; string str[110]; node(){} node(int x,int y,int step):x(x),y(y),step(step){} }; int A,B,C; bool vis[110][110]; bool bfs(){ memset(vis,false,sizeof(vis)); queue<node>qu; node p,q; // p=(0,0,0); p.x = 0,p.y = 0,p.step = 0; vis[0][0]=true; qu.push(p); while(!qu.empty()){ p = qu.front(); qu.pop(); if(p.x==C||p.y==C){ cout<<p.step<<endl; for(int i=1; i<=p.step; i++) cout<<p.str[i]<<endl; return true; } if(p.x==0){ q = p; q.x = A; q.step++; q.str[q.step] = "FILL(1)"; if(!vis[q.x][q.y]){ vis[q.x][q.y] = 1; qu.push(q); } }else if(p.x<=A){ q = p; q.x = 0; q.step++; q.str[q.step] = "DROP(1)"; if(!vis[q.x][q.y]){ vis[q.x][q.y]=1; qu.push(q); } if(p.y<B){ q = p; if(q.x+q.y<=B){ q.y += q.x; q.x = 0; }else{ q.x = (q.x+q.y)-B; q.y = B; } q.step++; q.str[q.step]="POUR(1,2)"; if(!vis[q.x][q.y]){ vis[q.x][q.y] = true; qu.push(q); } } } if(p.y==0){ q = p; q.y = B; q.step++; q.str[q.step] = "FILL(2)"; if(!vis[q.x][q.y]){ vis[q.x][q.y] = true; qu.push(q); } }else if(p.y<=B){ q = p; q.y = 0; q.step++; q.str[q.step] = "DROP(2)"; if(!vis[q.x][q.y]){ vis[q.x][q.y] = true; qu.push(q); } if(p.x<A){ q = p; if(q.y+q.x<=A){ q.x+=q.y; q.y = 0; }else{ q.y = (q.x+q.y)-A; q.x = A; } q.step++; q.str[q.step] = "POUR(2,1)"; if(!vis[q.x][q.y]){ vis[q.x][q.y] = true; qu.push(q); } } } } return false; } int main(){ while(~scanf("%d%d%d",&A,&B,&C)){ bool fuck = bfs(); if(!fuck){ puts("impossible"); } } return 0; }
标签:
原文地址:http://blog.csdn.net/just_sort/article/details/51366378