【HDOJ】2405 Marbles in Three Baskets
BFS+状态压缩。
1 /* 2405 */ 2 #include <iostream> 3 #include <queue> 4 #include <cstdio> 5 #include <cstring> 6 #include <cstdlib> 7 using namespace std; 8 9 #define MAXN 216000 10 #define MAXM 2005 11 12 typedef struct { 13 int a, b, c; 14 } node_t; 15 16 node_t Q[MAXM]; 17 int pre[MAXM]; 18 int sum; 19 int front, rear; 20 bool visit[MAXN]; 21 22 int bfs() { 23 int i, j, k; 24 node_t nd, tmp; 25 26 sum = Q[0].a + Q[0].b + Q[0].c; 27 if (sum % 3) 28 return 0; 29 if (Q[0].a == Q[0].b && Q[0].b == Q[0].c) 30 return 0; 31 32 front = 0; 33 rear = 1; 34 memset(visit, false, sizeof(visit)); 35 k = Q[0].a*3600 + Q[0].b*60 + Q[0].c; 36 visit[k] = true; 37 38 while (front < rear) { 39 // move from b to a 40 nd = Q[front]; 41 if (nd.b > nd.a) { 42 nd.b -= nd.a; 43 nd.a += nd.a; 44 k = nd.a*3600 + nd.b*60 + nd.c; 45 if (visit[k] == false) { 46 visit[k] = true; 47 Q[rear] = nd; 48 pre[rear] = front; 49 ++rear; 50 } 51 if (nd.a==nd.b && nd.b==nd.c) 52 return rear-1; 53 } 54 // move from c to a 55 nd = Q[front]; 56 if (nd.c > nd.a) { 57 nd.c -= nd.a; 58 nd.a += nd.a; 59 k = nd.a*3600 + nd.b*60 + nd.c; 60 if (visit[k] == false) { 61 visit[k] = true; 62 Q[rear] = nd; 63 pre[rear] = front; 64 ++rear; 65 } 66 if (nd.a==nd.b && nd.b==nd.c) 67 return rear-1; 68 } 69 // move from a to b 70 nd = Q[front]; 71 if (nd.a > nd.b) { 72 nd.a -= nd.b; 73 nd.b += nd.b; 74 k = nd.a*3600 + nd.b*60 + nd.c; 75 if (visit[k] == false) { 76 visit[k] = true; 77 Q[rear] = nd; 78 pre[rear] = front; 79 ++rear; 80 } 81 if (nd.a==nd.b && nd.b==nd.c) 82 return rear-1; 83 } 84 // move from c to b 85 nd = Q[front]; 86 if (nd.c > nd.b) { 87 nd.c -= nd.b; 88 nd.b += nd.b; 89 k = nd.a*3600 + nd.b*60 + nd.c; 90 if (visit[k] == false) { 91 visit[k] = true; 92 Q[rear] = nd; 93 pre[rear] = front; 94 ++rear; 95 } 96 if (nd.a==nd.b && nd.b==nd.c) 97 return rear-1; 98 } 99 // move from a to c 100 nd = Q[front]; 101 if (nd.a > nd.c) { 102 nd.a -= nd.c; 103 nd.c += nd.c; 104 k = nd.a*3600 + nd.b*60 + nd.c; 105 if (visit[k] == false) { 106 visit[k] = true; 107 Q[rear] = nd; 108 pre[rear] = front; 109 ++rear; 110 } 111 if (nd.a==nd.b && nd.b==nd.c) 112 return rear-1; 113 } 114 // move from b to c 115 nd = Q[front]; 116 if (nd.b > nd.c) { 117 nd.b -= nd.c; 118 nd.c += nd.c; 119 k = nd.a*3600 + nd.b*60 + nd.c; 120 if (visit[k] == false) { 121 visit[k] = true; 122 Q[rear] = nd; 123 pre[rear] = front; 124 ++rear; 125 } 126 if (nd.a==nd.b && nd.b==nd.c) 127 return rear-1; 128 } 129 ++front; 130 } 131 132 return 0; 133 } 134 135 void printPath(int x) { 136 if (pre[x] != -1) 137 printPath(pre[x]); 138 printf("%4d %3d %3d\n", Q[x].a, Q[x].b, Q[x].c); 139 } 140 141 int main() { 142 int i, j, k; 143 144 #ifndef ONLINE_JUDGE 145 freopen("data.in", "r", stdin); 146 freopen("data.out", "w", stdout); 147 #endif 148 149 pre[0] = -1; 150 while (scanf("%d %d %d", &Q[0].a, &Q[0].b, &Q[0].c) != EOF) { 151 k = bfs(); 152 printPath(k); 153 puts("============"); 154 } 155 156 return 0; 157 }