poj 3414 Pots bfs+模拟
1 #include<iostream> 2 #include<cstring> 3 #define fillA 1 4 #define pourAB 2 5 #define dropA 3 6 #define fillB 4 7 #define pourBA 5 8 #define dropB 6 9 10 #define N 10000 11 12 using namespace std; 13 int vis[105][105]; 14 class node 15 { 16 public: 17 int A, B; 18 int dir; 19 node() 20 { 21 A=0; 22 B=0; 23 } 24 }; 25 26 int a, b, c, tot; 27 node q[N]; 28 int pre[N]; 29 30 void printPath(int index) 31 { 32 if(index==0) 33 { 34 cout<<tot<<endl; 35 return ; 36 } 37 ++tot; 38 printPath(pre[index]); 39 switch(q[index].dir) 40 { 41 case 1: 42 cout<<"FILL(1)"; 43 break; 44 case 2: 45 cout<<"POUR(1,2)"; 46 break; 47 case 3: 48 cout<<"DROP(1)"; 49 break; 50 case 4: 51 cout<<"FILL(2)"; 52 break; 53 case 5: 54 cout<<"POUR(2,1)"; 55 break; 56 case 6: 57 cout<<"DROP(2)"; 58 break; 59 } 60 cout<<endl; 61 } 62 63 int bfs() 64 { 65 int head=0, rear=1, r; 66 node cur, next; 67 memset(vis, 0, sizeof(vis)); 68 pre[0]=0; 69 vis[0][0]=1; 70 while(head<rear) 71 { 72 cur=q[head]; 73 if(cur.A==c || cur.B==c) 74 { 75 printPath(head); 76 return 1; 77 } 78 next=cur; 79 if(!vis[a][cur.B])//将 A 装满 80 { 81 next.A=a; 82 next.dir=fillA; 83 pre[rear]=head; 84 vis[a][cur.B]=1; 85 q[rear++]=next; 86 } 87 if(!vis[0][cur.B])//将 A 倒掉 88 { 89 next.A=0; 90 next.dir=dropA; 91 pre[rear]=head; 92 vis[0][cur.B]=1; 93 q[rear++]=next; 94 } 95 r=b-cur.B; 96 next.dir=pourAB; 97 if(r>cur.A && !vis[0][cur.B+cur.A])//将A 倒向 B 98 { 99 next.A=0; 100 next.B=cur.B+cur.A; 101 pre[rear]=head; 102 q[rear++]=next; 103 vis[0][cur.B+cur.A]=1; 104 } 105 else if(r<=cur.A && !vis[cur.A-r][cur.B+r]) 106 { 107 next.A=cur.A-r; 108 next.B=cur.B+r; 109 pre[rear]=head; 110 q[rear++]=next; 111 vis[cur.A-r][cur.B+r]=1; 112 } 113 114 next=cur;//开始错在这里了, 忘记了从新给next赋值了 115 if(!vis[cur.A][b])//将 B 装满 116 { 117 next.B=b; 118 next.dir=fillB; 119 pre[rear]=head; 120 q[rear++]=next; 121 vis[cur.A][b]=1; 122 } 123 if(!vis[cur.A][0])//将 B 倒掉 124 { 125 next.B=0; 126 next.dir=dropB; 127 pre[rear]=head; 128 q[rear++]=next; 129 vis[cur.A][0]=1; 130 } 131 r=a-cur.A; 132 next.dir=pourBA; 133 if(r>cur.B && !vis[cur.B+cur.A][0])//将B 倒向 A 134 { 135 next.B=0; 136 next.A=cur.B+cur.A; 137 pre[rear]=head; 138 q[rear++]=next; 139 vis[cur.B+cur.A][0]=1; 140 } 141 else if(r<=cur.B && !vis[cur.A+r][cur.B-r]) 142 { 143 next.A=cur.A+r; 144 next.B=cur.B-r; 145 pre[rear]=head; 146 q[rear++]=next; 147 vis[cur.A+r][cur.B-r]=1; 148 } 149 ++head; 150 } 151 return 0; 152 } 153 154 int main() 155 { 156 while(cin>>a>>b>>c) 157 { 158 tot=0; 159 if(c>a && c>b) 160 { 161 cout<<"impossible"<<endl; 162 continue; 163 } 164 if(!bfs()) 165 cout<<"impossible"<<endl; 166 } 167 return 0; 168 }
本文来自博客园,作者:hjzqyx,转载请注明原文链接:https://www.cnblogs.com/hujunzheng/p/3782823.html