Poj--2133(BFS)

2014-12-19 00:59:38

思路:因为状态总数最多为2^16,所以用vis[]数组记录该状态是否存在即可,用BFS搜索(这样能记录步数)

  注意:此题巨坑的一点是:如果所给的串已经有一个串和goal ID相同,那么答案应该是2。。。。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <queue>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 #define getmid(l,r) (l + (r - l) / 2)
 8 #define MP(a,b) make_pair(a,b)
 9 typedef pair<int,int> pii;
10 const int INF = 1 << 30;
11 
12 bool vis[70000];
13 int B,E,g,id[110],step,dif;
14 char goal[20],ans[20],tmp[20];
15 queue<pii> Q;
16 
17 void Judge(pii x){
18     for(int i = B - 1; i >= 0; --i){
19         tmp[i] = '0' + (x.first & 1);
20         x.first >>= 1;
21     }
22     int cnt = 0;
23     for(int i = B - 1; i >= 0; --i) if(tmp[i] != goal[i]) cnt++;
24     if(cnt < dif) dif = cnt,strcpy(ans,tmp),step = x.second;
25     else if(cnt == dif){
26         if(x.second < step || (x.second == step && strcmp(tmp,ans) < 0))
27             strcpy(ans,tmp),step = x.second;
28     }
29 }
30 
31 void Bfs(){
32     while(!Q.empty()) Q.pop();
33     for(int i = 0; i < E; ++i){
34         Q.push(MP(id[i],0));
35         vis[id[i]] = true;
36     }
37     while(!Q.empty()){
38         pii x = Q.front();
39         Q.pop();
40         Judge(x);
41         for(int i = 0; i < E; ++i){
42             int v = x.first ^ id[i];
43             if(vis[v] == false){
44                 vis[v] = true;
45                 Q.push(MP(v,x.second + 1));
46             }
47         }
48     }
49 }
50 
51 int main(){
52     int v = 0,b = 1;
53     scanf("%d%d",&B,&E);
54     scanf("%s",goal);
55     for(int i = B - 1; i >= 0; --i){
56         if(tmp[i] == '1') v += b;
57         b <<= 1;
58     }
59     g = v;
60     for(int i = 0; i < E; ++i){
61         scanf("%s",tmp);
62         v = 0,b = 1;
63         for(int j = B - 1; j >= 0; --j){
64             if(tmp[j] == '1') v += b;
65             b <<= 1;
66         }
67         id[i] = v;
68     }
69     dif = INF;
70     ans[0] = '2';
71     Bfs();
72     if(!step) step += 2;
73     printf("%d\n",step);
74     ans[B] = '\0';
75     printf("%s\n",ans);
76     return 0;
77 }

 

posted @ 2014-12-19 01:01  Naturain  阅读(138)  评论(0编辑  收藏  举报