【HDOJ】3088 WORM

状态压缩+BFS。

  1 /* 3088 */
  2 #include <iostream>
  3 #include <cstdio>
  4 #include <cstring>
  5 #include <cstdlib>
  6 #include <queue>
  7 using namespace std;
  8 
  9 #define MAXN 60000
 10 #define MAXL 11
 11 
 12 typedef struct {
 13     char s[MAXL];
 14     int t;
 15 } node_t;
 16 
 17 node_t bn;
 18 bool visit[MAXN];
 19 int end[3];
 20 int len;
 21 
 22 int cal(char *s) {
 23     int i, ret = 0;
 24     
 25     for (i=0; i<len; ++i)
 26         ret = 3*ret + s[i];
 27     return ret;
 28 }
 29 
 30 int bfs() {
 31     int i, j, k, v;
 32     int pre, cur;
 33     queue<node_t> Q;
 34     node_t nd;
 35     
 36     v = cal(bn.s);
 37     if (v == end[0] || v==end[1] || v==end[2])
 38         return 0;
 39     memset(visit, false, sizeof(visit));
 40     visit[v] = true;
 41     Q.push(bn);
 42     
 43     while (!Q.empty()) {
 44         nd = Q.front();
 45         Q.pop();
 46         for (i=1; i<len; ++i) {
 47             if (nd.s[i] == nd.s[i-1])
 48                 continue;
 49             pre = nd.s[i-1];
 50             cur = nd.s[i];
 51             nd.s[i] = nd.s[i-1] = 3-(pre+cur);
 52             v = cal(nd.s);
 53             if (visit[v] == false) {
 54                 if (v==end[0] || v==end[1] || v==end[2])
 55                     return nd.t + 1;
 56                 ++nd.t;
 57                 visit[v] = true;
 58                 Q.push(nd);
 59                 --nd.t;
 60             }
 61             nd.s[i-1] = pre;
 62             nd.s[i] = cur;
 63         }
 64     }
 65     
 66     return -1;
 67 }
 68 
 69 void init() {
 70     int i, j, k;
 71     
 72     end[0] = 0;
 73     for (i=1; i<3; ++i) {
 74         k = 0;
 75         for (j=0; j<len; ++j)
 76             k = 3*k + i;
 77         end[i] = k;
 78     }
 79 }
 80 
 81 int main() {
 82     int t;
 83     int i, j, k;
 84     
 85     #ifndef ONLINE_JUDGE
 86         freopen("data.in", "r", stdin);
 87         freopen("data.out", "w", stdout);
 88     #endif
 89     
 90     scanf("%d", &t);
 91     bn.t = 0;
 92     while (t--) {
 93         scanf("%s", bn.s);
 94         len = strlen(bn.s);
 95         init();
 96         for (i=0; i<len; ++i) {
 97             if (bn.s[i] == 'r')    bn.s[i] = 0;
 98             if (bn.s[i] == 'g')    bn.s[i] = 1;
 99             if (bn.s[i] == 'b')    bn.s[i] = 2;
100         }
101         k = bfs();
102         if (k < 0)
103             puts("No solution!");
104         else
105             printf("%d\n", k);
106     }
107     
108     return 0;
109 }

 

posted on 2015-02-15 10:39  Bombe  阅读(128)  评论(0编辑  收藏  举报

导航