poj 3414 pots
-
You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
- FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
- DROP(i) empty the pot i to the drain;
- POUR(i,j) pour from pot i to pot j; after this operation either the pot j is full (and there may be some water left in the pot i), or the pot i is empty (and all its contents have been moved to the pot j).
Write a program to find the shortest possible sequence of these operations that will yield exactly C liters of water in one of the pots.
遇到的问题:
如何合理的拓展;分成8中情况一种种考虑;
View Code1 #include<cstring> 2 #include<iostream> 3 #include<cstdio> 4 #include<stack> 5 using namespace std; 6 const int N = 111; 7 bool vis[N][N]; 8 int A, B, C; 9 struct state 10 { 11 int x, y, step, pre, id; 12 state() { } 13 state(int xx, int yy, int s, int p, int i): x(xx), y(yy), step(s), pre(p), id(i) { } 14 }q[N*N]; 15 void print(state over) { 16 cout << over.step << endl; 17 stack<int> ans; 18 while (over.step) { 19 ans.push(over.id); 20 over = q[over.pre]; 21 } 22 while (!ans.empty()) { 23 int t = ans.top(); 24 ans.pop(); 25 switch (t) 26 { 27 case 1: 28 printf("FILL(1)\n"); break; 29 case 2: 30 printf("FILL(2)\n"); break; 31 case 3: 32 printf("DROP(1)\n"); break; 33 case 4: 34 printf("DROP(2)\n"); break; 35 case 5: 36 printf("POUR(1,2)\n"); break; 37 case 6: 38 printf("POUR(2,1)\n"); break; 39 } 40 } 41 } 42 bool bfs() { 43 memset(vis, 0, sizeof(vis)); 44 int head = 0, tail = 0; 45 q[tail++] = state(0, 0, 0, -1, -1); 46 while (head < tail) { 47 state t = q[head]; 48 int a = t.x, b = t.y, step = t.step; 49 if (a == C || b == C) { 50 print(t); 51 return true; 52 } 53 if (!vis[A][b]) { //FILL(1) 54 vis[A][b] = 1; 55 q[tail++] = state(A, b, step + 1, head, 1); 56 } 57 if (!vis[a][B]) { //FILL(2) 58 vis[a][B] = 1; 59 q[tail++] = state(a, B, step + 1, head, 2); 60 } 61 if (!vis[0][b]) { //drop(1) 62 vis[0][b] = 1; 63 q[tail++] = state(0, b, step + 1, head, 3); 64 } 65 if (!vis[a][0]) { //drop(2) 66 vis[a][0] = 1; 67 q[tail++] = state(a, 0, step + 1, head, 4); 68 } 69 if (b + a > B && !vis[a - (B - b)][B]) { //pour(1, 2) 1杯有剩余 70 vis[a - B + b][B] = 1; 71 q[tail++] = state(a - B + b, B, step + 1, head, 5); 72 } 73 if (b + a <= B && !vis[0][a + b]) { //pour(1, 2) , 1杯没有剩余; 74 vis[0][a + b] = 1; 75 q[tail++] = state(0, a + b, step + 1, head, 5); 76 } 77 if (b + a > A && !vis[A][b - A + a]) { //pour(2, 1) 78 vis[A][b - A + a] = 1; 79 q[tail++] = state(A, b - A + a, step + 1, head, 6); 80 } 81 if (b + a <= A && !vis[a + b][0]) { //2杯没有剩余; 82 vis[a + b][0] = 1; 83 q[tail++] = state(a + b, 0, step + 1, head, 6); 84 } 85 head++; 86 } 87 return false; 88 } 89 90 int main() { 91 cin >> A >> B >> C; 92 if (!bfs()) 93 cout << "impossible!" << endl; 94 return 0; 95 }


浙公网安备 33010602011771号