BFS很簡單的思想,但是注意剪枝,因為很多會重復,比如,不斷的empty,這個重復很嚴重,所以很有必要去除重復,即記錄1000 *1000的矩陣,保證對想通的a,b不重復計算
#include#include #include #include 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 op; }; void Cal(int a,int b,int q) { queue 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