poj3414 Pots(BFS)
题目链接
http://poj.org/problem?id=3414
题意
有两个杯子,容量分别为A升,B升,可以向杯子里倒满水,将杯子里的水倒空,将一个杯子里的水倒到另一个杯子里,求怎样倒才能使其中的一个杯子里的水恰为C升,输出最少步数和操作;如果不能倒到C升,输出“impossible”。
思路
这题与poj1606基本相同,在poj1606的基础上添加了输出最少步数,修改了操作的表示,以及不可能达到目标时输出impossible。将poj1606的代码略作修改即可。
代码
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 #include <stack> 6 using namespace std; 7 8 struct Node 9 { 10 int a, b; 11 int steps; 12 int flag; 13 Node* pre; 14 }; 15 16 const int N = 1010; 17 int ca, cb, n; 18 int visit[N][N]; 19 stack<int> s; 20 21 void print() 22 { 23 while (!s.empty()) 24 { 25 switch (s.top()) 26 { 27 case 0: 28 cout << "FILL(1)" << endl; 29 break; 30 case 1: 31 cout << "FILL(2)" << endl; 32 break; 33 case 2: 34 cout << "DROP(1)" << endl; 35 break; 36 case 3: 37 cout << "DROP(2)" << endl; 38 break; 39 case 4: 40 cout << "POUR(1,2)" << endl; 41 break; 42 case 5: 43 cout << "POUR(2,1)" << endl; 44 break; 45 } 46 s.pop(); 47 } 48 } 49 50 void bfs(int a, int b) 51 { 52 Node state[N]; 53 int cnt = -1; 54 memset(visit, 0, sizeof(visit)); 55 Node node; 56 node.a = node.b = 0; 57 node.steps = 0; 58 node.pre = NULL; 59 queue<Node> q; 60 q.push(node); 61 visit[node.a][node.b] = 1; 62 while (!q.empty()) 63 { 64 Node node = q.front(); 65 q.pop(); 66 state[++cnt] = node; 67 Node next = node; 68 for (int i = 0; i < 6; i++) 69 { 70 next = node; 71 int amount; 72 switch (i) 73 { 74 case 0: //FILL(1) 75 next.a = ca; 76 next.flag = 0; 77 break; 78 case 1: //FILL(2) 79 next.b = cb; 80 next.flag = 1; 81 break; 82 case 2: // DROP(1) 83 next.a = 0; 84 next.flag = 2; 85 break; 86 case 3: //DROP(2) 87 next.b = 0; 88 next.flag = 3; 89 break; 90 case 4: //POUR(1,2) 91 amount = cb - node.b; 92 if (node.a > amount) 93 { 94 next.a -= amount; 95 next.b = cb; 96 } 97 else { 98 next.a = 0; 99 next.b = node.a + node.b; 100 } 101 next.flag = 4; 102 break; 103 case 5: //POUR(2,1) 104 amount = ca - node.a; 105 if (node.b > amount) 106 { 107 next.a = ca; 108 next.b -= amount; 109 } 110 else { 111 next.a = node.a + node.b; 112 next.b = 0; 113 } 114 next.flag = 5; 115 break; 116 } 117 118 if (!visit[next.a][next.b]) 119 { 120 visit[next.a][next.b] = 1; 121 next.pre = &state[cnt]; 122 next.steps = node.steps + 1; 123 if (next.a == n || next.b == n) 124 { 125 cout << next.steps << endl; 126 while (next.pre) 127 { 128 s.push(next.flag); 129 next = *next.pre; 130 } 131 print(); 132 return; 133 } 134 q.push(next); 135 } 136 } 137 } 138 cout << "impossible" << endl; 139 } 140 141 int main() 142 { 143 cin >> ca >> cb >> n; 144 bfs(0, 0); 145 return 0; 146 }
相似题目
本站使用「CC BY-NC-SA」创作共享协议,转载请在文章明显位置注明作者及出处。