http://poj.org/problem?id=3087
注意复制字符串的时候,要在末尾加上'\0',否则导致strcmp出错。
还有就是开数组大小的时候看清楚一点,别开错了debug了好久。
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 #include<algorithm> 6 #include<cmath> 7 #include<set> 8 #define IO ios::sync_with_stdio(false);cin.tie(0); 9 #define INF 0x3f3f3f3f3f3f3f3f 10 typedef long long ll; 11 using namespace std; 12 int t, n, k, kase=0; 13 char s12[210], s1[110], s2[110]; 14 char vis[1010][210]; 15 typedef struct{ 16 int cnt; 17 char s[210]; 18 }Node; 19 int panduan(Node a) 20 { 21 if(!strcmp(s12, a.s)) 22 return 1; 23 return 0; 24 } 25 int panduan2(Node a) 26 { 27 for(int i = 0; i < k; i++){ 28 if(!strcmp(a.s, vis[i])){ 29 return 0; 30 } 31 } 32 return 1; 33 } 34 void bfs() 35 { 36 k=0; 37 int flag=0; 38 Node node; 39 queue<Node> q; 40 int j = 0; 41 for(int i = 0; i < 2*n; i += 2){ 42 node.s[i] = s2[j++]; 43 } 44 j = 0; 45 for(int i = 1; i < 2*n; i += 2){ 46 node.s[i] = s1[j++]; 47 } 48 node.s[2*n] = '\0'; 49 node.cnt=1; 50 q.push(node); 51 while(!q.empty()){ 52 Node t = q.front(), p; 53 strcpy(vis[k++], t.s); 54 q.pop(); 55 /*for(int i = 0; i < 2*n; i++){ 56 cout << t.s[i]; 57 } cout << endl;*/ 58 if(panduan(t)){ 59 flag=1; 60 cout << ++kase << " " << t.cnt << endl; 61 break; 62 } 63 //拆分 64 j=0; 65 for(int i = 0; i < n; i++){ 66 s1[j++] = t.s[i]; 67 } 68 j=0; 69 for(int i = n; i < 2*n; i++){ 70 s2[j++] = t.s[i]; 71 } 72 //合并 73 j=0; 74 for(int i = 0; i < 2*n; i += 2){ 75 p.s[i] = s2[j++]; 76 } 77 j = 0; 78 for(int i = 1; i < 2*n; i += 2){ 79 p.s[i] = s1[j++]; 80 } 81 p.s[2*n] = '\0'; 82 p.cnt=t.cnt+1; 83 if(panduan2(p)){ 84 //strcpy(vis[k++], p.s); 85 q.push(p); 86 } 87 } 88 if(!flag){ 89 cout << ++kase << " " << "-1" << endl; 90 } 91 } 92 int main() 93 { 94 cin >> t; 95 while(t--){ 96 cin >> n; 97 cin >> s1 >> s2 >> s12; 98 memset(vis, 0, sizeof(vis)); 99 //cout << ++kase << " "; 100 bfs(); 101 } 102 return 0; 103 }