POJ 3434 Pots bfs

http://poj.org/problem?id=3414

题意:给出两个杯子a,b,六种操作,问能否得到c升水  如果可以求最少步数 并输出过程  否则输出impossible

  值得品味的一道题 

代码:

  1 #include<iostream>
2 #include<cstdio>
3 #include<string>
4 #include<cstring>
5 #define Min(a,b)a<b?a:b
6 #define MAX 105
7 using namespace std;
8 int a,b,c;
9 bool vs[MAX][MAX];
10 char str[6][10]={"FILL(1)","FILL(2)","DROP(1)","DROP(2)",
11 "POUR(1,2)","POUR(2,1)"};
12 structnode
13 {
14 int ope,a,b,step;
15 node *pre;
16 }qu[MAX*MAX];
17
18 void print(node now)//输出很有技巧 看一大神的思路
19 {
20 if(now.pre!=NULL)
21 {
22 print(*now.pre);
23 printf("%s\n",str[now.ope]);
24 }
25
26 }
27
28 void bfs()//六种操作
29 {
30 int beg=0,end=0;
31 qu[beg].a=qu[beg].b=0;
32 qu[beg].step=0;
33 qu[beg].pre=NULL;
34 while(beg<=end)
35 {
36 node t=qu[beg];
37 if(t.a==c||t.b==c)
38 {
39 printf("%d\n",t.step);
40 print(t);
41 return ;
42 }
43
44 if(!vs[a][t.b])
45 {
46 end++;
47 qu[end].ope=0;
48 qu[end].a=a;
49 qu[end].b=t.b;
50 qu[end].step=t.step+1;
51 qu[end].pre=&qu[beg];
52 vs[a][t.b]=1;
53 }
54 if(!vs[t.a][b])
55 {
56 end++;
57 qu[end].ope=1;
58 qu[end].a=t.a;
59 qu[end].b=b;
60 qu[end].step=t.step+1;
61 qu[end].pre=&qu[beg];
62 vs[t.a][b]=1;
63 }
64 if(!vs[0][t.b])
65 {
66 end++;
67 qu[end].ope=2;
68 qu[end].a=0;
69 qu[end].b=t.b;
70 qu[end].step=t.step+1;
71 qu[end].pre=&qu[beg];
72 vs[0][t.b]=1;
73 }
74 if(!vs[t.a][0])
75 {
76 end++;
77 qu[end].ope=3;
78 qu[end].a=t.a;
79 qu[end].b=0;
80 qu[end].step=t.step+1;
81 qu[end].pre=&qu[beg];
82 vs[t.a][0]=1;
83 }
84 int min1=Min(t.a,b-t.b);
85 if(!vs[t.a-min1][t.b+min1])
86 {
87 end++;
88 qu[end].ope=4;
89 qu[end].a=t.a-min1;
90 qu[end].b=t.b+min1;
91 qu[end].step=t.step+1;
92 qu[end].pre=&qu[beg];
93 vs[t.a-min1][t.b+min1]=1;
94 }
95 int min2=Min(a-t.a,t.b);
96 if(!vs[t.a+min2][t.b-min2])
97 {
98 end++;
99 qu[end].ope=5;
100 qu[end].a=t.a+min2;
101 qu[end].b=t.b-min2;
102 qu[end].step=t.step+1;
103 qu[end].pre=&qu[beg];
104 vs[t.a+min2][t.b-min2]=1;
105 }
106 beg++;
107 }
108 printf("impossible\n");
109 return ;
110 }
111
112 int main()
113 {
114 scanf("%d%d%d",&a,&b,&c);
115 memset(vs,0,sizeof(vs));
116 bfs();
117
118 return 0;
119 }


posted @ 2012-03-02 00:09  快乐.  阅读(328)  评论(0编辑  收藏  举报