题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1495
有三个瓶子 A B C,每次都有6个状态
A->B A->C B->A B->C C->A C->B
用BFS跑一遍就行了
代码:
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <queue> 5 6 using namespace std; 7 8 const int inf = 0x3f; 9 const int INF = 0x3f3f3f3f; 10 const int maxn = 500; 11 struct Coke 12 { 13 int a, b, c; 14 int step; 15 }coke[maxn]; 16 17 int a, b, c, ok; 18 int Hash[maxn][maxn], dir[3]; 19 queue<Coke> q; 20 Coke now, Ne; 21 22 bool judge(int x, int y, int z) 23 { 24 //printf("In %d %d %d\n", x, y, z); 25 if(x < 0 || x > a) return false; 26 if(y < 0 || y > b) return false; 27 if(z < 0 || z > c) return false; 28 if(Hash[x][y]) return false; 29 Ne.a = x; Ne.b = y; Ne.c = z; Ne.step = now.step+1; 30 //printf("out %d %d %d\n", x, y, z); 31 Hash[x][y] = 1; 32 q.push(Ne); 33 if(x==a/2 && y==a/2) ok=1; 34 if(x==a/2 && z==a/2) ok=1; 35 if(z==a/2 && y==a/2) ok=1; 36 return true; 37 } 38 int BFS() 39 { 40 while(!q.empty()) q.pop(); 41 42 int x, y, z, mi, ma; 43 Coke s; 44 s.a = a; s.b = 0; s.c = 0; s.step = 0; 45 q.push(s); 46 Hash[a][0] = 1; 47 while(!q.empty()) 48 { 49 now = q.front(); q.pop(); 50 Ne = now; 51 //a->b 52 mi = min(now.a, (b-now.b)); 53 x = now.a - mi; y = now.b + mi; z = now.c; 54 judge(x, y, z); 55 //a->c 56 mi = min(now.a, (c-now.c)); 57 x = now.a - mi; z = now.c + mi; y = now.b; 58 judge(x, y, z); 59 //b->a 60 mi = min(now.b, (a-now.a)); 61 y = now.b - mi; x = now.a + mi; z = now.c; 62 judge(x, y, z); 63 //b->c 64 mi = min(now.b, (c-now.c)); 65 y = now.b - mi; z = now.c + mi; x = now.a; 66 judge(x, y, z); 67 //c->a 68 mi = min(now.c, (a-now.a)); 69 z = now.c - mi; x = now.a + mi; y = now.b; 70 judge(x, y, z); 71 //c->b 72 mi = min(now.c, (b-now.b)); 73 z = now.c - mi; y = now.b + mi; x = now.a; 74 judge(x, y, z); 75 76 if(ok == 1) return now.step+1; 77 } 78 return 0; 79 } 80 81 int main() 82 { 83 while(scanf("%d %d %d", &a, &b, &c) && (a+b+c)) 84 { 85 if(a%2) 86 { 87 puts("NO"); continue; 88 } 89 ok = 0; 90 memset(Hash, 0, sizeof(Hash)); 91 int ans = 0; 92 if(ans = BFS()) printf("%d\n", ans); 93 else puts("NO"); 94 } 95 return 0; 96 }
原文:http://www.cnblogs.com/tenlee/p/4492489.html