BFS(倒水问题) HDU 1495 非常可乐
1 /*
2 BFS:倒水问题,当C是奇数时无解。一共有六种情况,只要条件符合就入队,我在当该状态vised时写了continue
3 结果找了半天才发现bug,泪流满面。。。。(网上找份好看的题解都难啊)
4 */
5 /************************************************
6 Author :Running_Time
7 Created Time :2015-8-4 10:54:16
8 File Name :HDOJ_1495.cpp
9 ************************************************/
10
11 #include <cstdio>
12 #include <algorithm>
13 #include <iostream>
14 #include <sstream>
15 #include <cstring>
16 #include <cmath>
17 #include <string>
18 #include <vector>
19 #include <queue>
20 #include <deque>
21 #include <stack>
22 #include <list>
23 #include <map>
24 #include <set>
25 #include <bitset>
26 #include <cstdlib>
27 #include <ctime>
28 using namespace std;
29
30 #define lson l, mid, rt << 1
31 #define rson mid + 1, r, rt << 1 | 1
32 typedef long long ll;
33 const int MAXN = 1e2 + 10;
34 const int INF = 0x3f3f3f3f;
35 const int MOD = 1e9 + 7;
36 struct Cola {
37 int a, b, c, step;
38 };
39 bool vis[MAXN][MAXN];
40 int A, B, C;
41
42 void BFS(void) {
43 memset (vis, false, sizeof (vis));
44 queue<Cola> Q; Q.push ((Cola) {0, 0, C, 0}); vis[0][0] = true;
45 while (!Q.empty ()) {
46 Cola c = Q.front (); Q.pop ();
47 if ((c.a == c.b && c.a == C / 2) || (c.a == c.c && c.a == C / 2) || (c.b == c.c && c.b == C / 2)) {
48 printf ("%d\n", c.step); return ;
49 }
50 if (c.c > 0) { //c -> a
51 int t = min (c.c, A - c.a);
52 if (!vis[c.a+t][c.b]) {
53 vis[c.a+t][c.b] = true; Q.push ((Cola) {c.a+t, c.b, c.c-t, c.step + 1});
54 }
55 }
56 if (c.c > 0) { //c -> b
57 int t = min (c.c, B - c.b);
58 if (!vis[c.a][c.b+t]) {
59 vis[c.a][c.b+t] = true; Q.push ((Cola) {c.a, c.b+t, c.c-t, c.step + 1});
60 }
61 }
62 if (c.a > 0) { //a -> c
63 int t = min (c.a, C - c.c);
64 if (!vis[c.a-t][c.b]) {
65 vis[c.a-t][c.b] = true; Q.push ((Cola) {c.a-t, c.b, c.c+t, c.step + 1});
66 }
67 }
68 if (c.b > 0) { //b -> c
69 int t = min (c.b, C - c.c);
70 if (!vis[c.a][c.b-t]) {
71 vis[c.a][c.b-t] = true; Q.push ((Cola) {c.a, c.b-t, c.c+t, c.step + 1});
72 }
73 }
74 if (c.a > 0) { //a -> b
75 int t = min (c.a, B - c.b);
76 if (!vis[c.a-t][c.b+t]) {
77 vis[c.a-t][c.b+t] = true; Q.push ((Cola) {c.a-t, c.b+t, c.c, c.step + 1});
78 }
79 }
80 if (c.b > 0) { //b -> a
81 int t = min (c.b, A - c.a);
82 if (!vis[c.a+t][c.b-t]) {
83 vis[c.a+t][c.b-t] = true; Q.push ((Cola) {c.a+t, c.b-t, c.c, c.step + 1});
84 }
85 }
86 }
87
88 puts ("NO");
89 }
90
91 int main(void) { //HDU 1495 非常可乐
92 while (scanf ("%d%d%d", &C, &A, &B) == 3) {
93 if (!C && !A && !B) break;
94 if (C & 1) {
95 puts ("NO"); continue;
96 }
97 BFS ();
98 }
99
100 return 0;
101 }
编译人生,运行世界!