Shuffle'm Up POJ - 3087 (简单广搜)

题目链接:https://cn.vjudge.net/problem/POJ-3087

作为这道题wa了八发的人有话要讲!!!仔细看题!仔细看题!仔细看题!

当S12拆分的时候,下面n个为S1,上面n个为S2

返回-1的条件是:组合成的S12重复出现了

注意:用string 类型变量存组合和拆分的串时,一定要清空!!! 

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <queue>
 5 #include <algorithm>
 6 #include <cmath>
 7 #include <map>
 8 #define mem(a,b) memset(a,b,sizeof(a));
 9 using namespace std;
10 #define INF 0x3f3f3f3f
11 typedef long long ll;
12 int dir[4][2] = {0,1,0,-1,1,0,-1,0};
13 const int maxn = 100005;
14 string s1,s2,s3,s;
15 int n,ans;
16 struct node
17 {
18     string x;
19     int y;//y代表花费
20     node(string xx,int yy):x(xx),y(yy) {};
21 };
22 map<string,bool>q;//用map来标记S12是否重复出现过
23 queue<node>q1;
24 void bfs(string p)
25 {
26     q1.push(node(p,1));
27     while(!q1.empty())
28     {
29         node k = q1.front();
30         q1.pop();
31         s1 = "";
32         s2 = "";
33         s  = "";
34         if(k.x == s3)
35         {
36             ans = k.y;
37             break;
38         }
39         for(int i = 0; i < n; i++)
40         {
41             s1 += k.x[i];
42         }
43         for(int i = n; i < 2*n; i++)
44         {
45             s2 += k.x[i];
46         }
47         for(int i = 0; i < n; i++)
48         {
49             s += s2[i];
50             s += s1[i];
51         }
52         if(q[s] == 0)
53         {
54             q[s] = 1;
55             q1.push(node(s,k.y+1));
56         }
57         else
58         {
59             ans = -1;
60             break;
61         }
62     }
63 }
64 int main()
65 {
66     int t,tt = 0;
67     cin >> t;
68     while(t--)
69     {
70         tt++;
71         ans = 0;
72         while(!q1.empty())
73             q1.pop();
74         q.clear();
75         s  = "";
76         cin >> n;
77         cin >> s1 >> s2 >> s3;
78         for(int i = 0; i < n; i++)
79         {
80             s += s2[i];
81             s += s1[i];
82         }
83         q[s] = 1;
84         bfs(s);
85         cout << tt << " " << ans << endl;
86     }
87 
88     return 0;
89 }

猜你喜欢

转载自www.cnblogs.com/LLLAIH/p/11359859.html