Luogu P1032 String Conversion

String titles are generally disgusting, especially when you're trying to do it with only native C chars.

Although the string class is convenient, it is much slower than char. But the advantage of being slow is that you can easily complete many operations. For example, it is very convenient to use string to implement the replacement operation in this problem.

This topic can actually be done with a two-way wide search, but I was lazy and wrote a one-way wide search.

In this question, I also adjusted nearly 1h because of the num-- of line 64. . .

 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 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325405585&siteId=291194637