Jiudu OJ; question 1147: Jugs, jiudu oj1147jugs
Original question link address: http://ac.jobdu.com/problem.php? Pid = 1, 1147
Reprinted please indicate this article link: http://blog.csdn.net/yangnanhai93/article/details/42016353
BFS is a simple idea, but pay attention to pruning, because many of them will repeat, for example, the constant empty, this repetition is very serious, so it is necessary to remove duplication, that is, record the matrix of 1000*1000, make sure that the desired a and B are not repeated.
#include <stdio.h>#include <queue>#include <string>#include <memory.h>using namespace std; string op[6]={"fill A","fill B","pour B A","pour A B","empty A","empty B"};bool visited[1001][1001];struct Node{ int left,right; vector<int> op;};void Cal(int a,int b,int q){ queue<Node> result; Node first,second; first.left=0; first.right=0; result.push(first); memset(visited,0,sizeof(visited)); while(!result.empty()) { first=result.front(); result.pop(); for(int i=0;i<6;i++) { second=first; switch (i) { case 0: second.left=a; break; case 1: second.right=b; break; case 2://pour b to a if(second.right<=a-second.left) { second.left=second.left+second.right; second.right=0; } else { second.right=second.right-(a-second.left); second.left=a; } break; case 3: if(second.left<=b-second.right) { second.right=second.right+second.left; second.left=0; } else { second.left=second.left-(b-second.right); second.right=b; } break; case 4: second.left=0; break; case 5: second.right=0; break; } second.op.push_back(i); if(second.right==q) { for(int i=0;i<second.op.size();i++) printf("%s\n",op[second.op[i]].c_str()); printf("success\n"); return; } else { if(!visited[second.left][second.right]) result.push(second); visited[second.left][second.right]=true; } } }}int main(){ int a,b,q; while(scanf("%d%d%d",&a,&b,&q)!=EOF) { Cal(a,b,q); } return 0;}/************************************************************** Problem: 1147 User: vincent_ynh Language: C++ Result: Accepted Time:10 ms Memory:2036 kb****************************************************************/