nyoj 21-三个水杯

 1 //105738 jiaolinfeng 三个水杯 Accepted  68  4212 C/C++ 12-15 08:56:02 
2 #include<iostream>
3 #include<cstdio>
4 #include<queue>
5 #include<string.h>
6 using namespace std;
7 typedef struct
8 {
9 int cur[3];
10 int v[3];
11 int step;
12 }State;
13 State begin, end;
14 queue<State> q;
15 int vis[1000010];
16 int final(State s1, State s2)
17 {
18 return (s1.cur[0] == s2.cur[0] && s1.cur[1] == s2.cur[1] && s1.cur[2] == s2.cur[2]);
19 }
20 int hash(State s)
21 {
22 return (s.cur[0] * 10000 + s.cur[1] * 100 + s.cur[2]);
23 }
24 int main()
25 {
26 int tcases, i, j, ok, min;
27 scanf("%d", &tcases);
28 while(tcases--)
29 {
30 scanf("%d%d%d", &begin.v[0], &begin.v[1], &begin.v[2]);
31 begin.cur[0] = begin.v[0];
32 begin.cur[1] = begin.cur[2] = 0;
33 begin.step = 0;
34 scanf("%d%d%d", &end.cur[0], &end.cur[1], &end.cur[2]);
35 ok = 0;
36 memset(vis, 0, sizeof(vis));
37 q.push(begin);
38 vis[myhash(begin)] = 1;
39 while(!q.empty())
40 {
41 State u = q.front();
42 q.pop();
43 if(final(u, end))
44 {
45 printf("%d\n", u.step);
46 ok = 1;
47 break;
48 }
49 for(i = 0; i <= 2; i++)
50 for(j = 0; j <= 2; j++)
51 if(i != j)
52 {
53 min = u.v[j] - u.cur[j];
54 if(u.cur[i] < min)
55 min = u.cur[i];
56 State v = u;
57 v.cur[i] -= min;
58 v.cur[j] += min;
59 v.step = u.step +1;
60 if(!vis[myhash(v)])
61 {
62 vis[myhash(v)] = 1;
63 q.push(v);
64 }
65 }
66 }
67 if(!ok)
68 {
69 printf("-1\n");
70 }
71 while(!q.empty())
72 {
73 q.pop();
74 }
75 }
76 return 0;
77 }



bfs的经典题...有向图的遍历...一直没写出来因为我没想出来状态之间如何区别,看了前辈的代码才恍然大悟...第一次用STL队列...以
后要继续努力!

posted @ 2011-12-15 09:01  枫萧萧  阅读(689)  评论(0编辑  收藏  举报