洛谷P1032 字串变换

字符串的题目一般都很恶心,特别是当你妄图只用原生c语言的char去做的时候。

string类虽然方便,但是相较于char慢很多。可是慢所带来的好处就是可以方便的完成很多操作。例如用string去实现这题中的替换操作时就会非常方便.

这个题目实际上还可以双向广搜去做,但是我懒,写了单向的广搜。

这题我还因为64行的 num-- 调了将近1h。。。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef unsigned long long ull;
 4 const int MAXN = 22;
 5 
 6 string A, B, rulef[7], rulet[7];
 7 int num = 1;
 8 
 9 struct P
10 {
11     string x;
12     int cnt;
13 };
14 
15 queue<P> q;
16 set<string> M;
17 int bfs()
18 {
19     P s;
20     s.x = A;
21     s.cnt = 0;
22 
23     M.insert(A);
24     q.push(s);
25     while(!q.empty())
26     {
27         P cur = q.front(); q.pop();
28         if(cur.x == B) return cur.cnt;
29         if(cur.cnt > 10) continue;
30 
31         for(int i = 1; i <= num; i++)
32         {
33             int len = rulef[i].length();
34             for(int j = 0; j <= (int) cur.x.length() - len; j++)
35             {
36                 if(cur.x.compare(j, len, rulef[i], 0, len) == 0)
37                 {
38                     P nxt;
39                     nxt = cur;
40                     nxt.x.replace(j, len, rulet[i]);
41                     if(M.find(nxt.x) == M.end())
42                     {
43                         M.insert(nxt.x);
44                         //cout<<nxt.x<<endl;
45                         nxt.cnt++;
46                         q.push(nxt);
47                     }
48                     
49                 }
50             }
51         }
52     }
53     return -1;
54 }
55 
56 int main()
57 {
58     //freopen("p1032.txt", "r", stdin);
59     cin>>A>>B;
60     //cout<<A<<" "<<B<<endl;
61     while(cin>>rulef[num]>>rulet[num]) 
62         //cout<<rulef[num]<<" "<<rulet[num]<<" "<<num<<endl;
63         num++;
64     num--;
65     //cout<<num<<endl;
66     //for(int i = 1; i <= num; i++)
67     //    cout<<rulef[i]<<" "<<rulet[i]<<endl;
68 
69     int ans = bfs();
70     if(ans == -1) cout<<"NO ANSWER!"<<endl;
71     else cout<<ans<<endl;
72     return 0;
73 }
原文地址:https://www.cnblogs.com/wsmrxc/p/8999168.html