1495 (BFS + 6种状态) 非常可乐

  1 #include <iostream>
2 #include <cstdio>
3 #include <cstring>
4
5 using namespace std;
6 const int N = 100000;
7 struct coco
8 {
9 int s;
10 int m;
11 int n;
12 int step;
13 }q[N];
14
15 int s, m, n;
16 int vis[101][101];
17
18 int bfs()
19 {
20 coco p, t;
21 int cnt, r = 0, f = 0;
22 q[0].s = s;
23 q[0].m = 0;
24 q[0].n = 0;
25 q[0].step = 0;
26 vis[m][n] = 1;
27 r++;
28 while(f < r)
29 {
30 p = q[f++];
31 cnt = 0;
32 if(p.s == s/2) cnt++;
33 if(p.m == s/2) cnt++;
34 if(p.n == s/2) cnt++;
35 if(cnt == 2) //satisfied the term
36 return p.step;
37 if(p.s)
38 {
39 t = p;
40 if(t.m < m) //s -> m
41 {
42 if(t.m + t.s > m)
43 {
44 t.s -= (m-t.m);
45 t.m = m;
46 }
47 else
48 {
49 t.m += t.s;
50 t.s = 0;
51 }
52 t.step++;
53 if(!vis[p.m][p.n])
54 {
55 vis[p.m][p.n] = 1;
56 q[r++] = t;
57 }
58 }
59 t = p;
60 if(t.n < n) //s -> n
61 {
62 if(t.n + t.s > n)
63 {
64 t.s -= (n-t.n);
65 t.n = n;
66 }
67 else
68 {
69 t.m += t.s;
70 t.s = 0;
71 }
72 t.step++;
73 if(!vis[t.m][t.n])
74 {
75 vis[t.m][t.n] = 1;
76 q[r++] = t;
77 }
78 }
79 }
80 if(p.m)
81 {
82 t = p; //m -> n
83 if(t.n < n)
84 {
85 if(t.n + t.m > n)
86 {
87 t.m -= (n-t.n);
88 t.n = n;
89 }
90 else
91 {
92 t.n += t.m;
93 t.m = 0;
94 }
95 t.step ++;
96 if(!vis[t.m][t.n])
97 {
98 vis[t.m][t.n] = 1;
99 q[r++] = t;
100 }
101 }
102
103 t = p; // m -> s
104 t.s += t.m;
105 t.m = 0;
106 t.step ++;
107 if(!vis[t.m][t.n])
108 {
109 vis[t.m][t.n] = 1;
110 q[r++] = t;
111 }
112 }
113 if(p.n)
114 {
115 t = p; // n -> m
116 if(t.n + t.m > m)
117 {
118 t.n -= (m - t.m);
119 t.m = m;
120 }
121 else
122 {
123 t.m += t.n;
124 t.n = 0;
125 }
126 t.step ++;
127 if(!vis[t.m][t.n])
128 {
129 vis[t.m][t.n] = 1;
130 q[r++] = t;
131 }
132
133 t = p; //n -> s
134 t.s += t.n;
135 t.n = 0;
136 t.step ++;
137 if(!vis[t.m][t.n])
138 {
139 vis[t.m][t.n] = 1;
140 q[r++] = t;
141 }
142 }
143 }
144 return 0;
145 }
146
147 int main()
148 {
149 //freopen("data.in", "r", stdin);
150
151 int ans;
152 while(scanf("%d%d%d", &s, &n, &m), s||n||m)
153 {
154 memset(vis, 0, sizeof(vis));
155 if(m > n)
156 {
157 m = m+n;
158 n = m-n;
159 m = m-n;
160 }
161 if(s&1) //if 's' is odd
162 {
163 printf("NO\n");
164 continue;
165 }
166 ans = bfs();
167 if(ans)
168 printf("%d\n", ans);
169 else
170 printf("NO\n");
171 }
172 return 0;
173 }

 

posted on 2012-03-14 16:15  万里心晴  阅读(264)  评论(0编辑  收藏  举报