Title: give you two cups, each time you can fill a cup, empty, or pour one cup of water into another cup;
Make one cup full or another cup empty, and the minimum number of operations makes the water in the B cup the target value.
Analysis: Search. Han Xin is a horse of oil.
Set state (A, b) is twice times the water capacity, then up to 1 million states, BFS to find the shortest path (the least number of operations).
Description: The code that was written many years ago was optimized for a bit (⊙_⊙).
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio>using namespace std ;/* Action number: *fill a--------0 *fill b--------1 *empty a--------2 *empty b--------3 *pour A b--------4 *pour b A--------5 */int ca,cb,n;int used[1001][1001]; /* Mark weight */typedef struct queue{int a,b,p,o;}; Queue q[1000001];void output (int i) {if (i < 0) return;else {output (Q[I].P); switch (Q[I].O) {case 0:cout << fill A\n "; Break;case 1:cout << "Fill b\n"; Break;case 2:cout << "Empty a\n"; Break;case 3:cout << "Empty b\n"; Break;case 4:cout << "pour A b\n"; Break;case 5:cout << "pour B a\n"; Break;}}} void Search (int Ca, int Cb, int T) {memset (used, 0, sizeof (used)); used[0][0] = 1; q[0].a = q[0].b = 0; Q[0].P = Q[0].O = -1;int move = 0,save = 1;while (Move < Save) {Queue now = Q[move ++];for (int i = 0; i < 6; + + I {Queue New = now; NEW.O = i; NEW.P = Move-1;switch (i) {case 0:if (now.a! = Ca &&Now.b! = cb) NEW.A = Ca;break;case 1:if (now.a! = Ca && now.b! = cb) new.b = Cb;break;case 2:if (now.a && ; NOW.B) NEW.A = 0;break;case 3:if (now.a && now.b) new.b = 0;break;case 4:if (now.b! = Cb) if (now.b + now.a <= C b) {new.b = now.a + now.b; NEW.A = 0;} else {new.b = Cb; NEW.A = NOW.A-CB + now.b;} Break;case 5:if (NOW.A! = CA) if (NOW.A + now.b <= CA) {NEW.A = now.b + now.a; new.b = 0;} else {new.a = Ca; new.b = Now.b-ca + now.a;} break;} if (!used[new.a][new.b]) {used[new.a][new.b] = 1; Q[save + +] = new;if (new.b = = T) {output (save-1); cout << "success\n"; return;}}}} int main () {while (CIN >> CA >> CB >> N) Search (CA, CB, n); return 0;}
UVa 571-jugs