【题解】luogu p1032 字串变换
总结:
1.bfs的模板没有掌握好
2.string s 的时候可以用s[m]=x 将s字符串中的m位置的字符改变成x字符
一道简单的bfs
#include<bits/stdc++.h> using namespace std; string s1, s2; string a[10], b[10]; int cnt = 1, m; queue <string> q; queue <int> num; map <string, int> mapp; int bfs() { string s, ss; while(q.empty() == 0 && q.front() != s2 && num.front() <= 10) { if(mapp[q.front()] == 1) { q.pop(); num.pop(); continue; } mapp[q.front()] = 1; for(int i = 1; i <= cnt; i++) { s = q.front(); while(1) { m = s.find(a[i]); if(m == -1) break; ss = q.front(); ss.replace(m, a[i].size(), b[i]); q.push(ss); num.push(num.front()+1); s[m] = '.'; } } q.pop(); num.pop(); } if(q.empty() == 1 || num.front() > 10) return -1; else return num.front(); } int main() { cin >> s1 >> s2; while(cin >> a[cnt] >> b[cnt]) cnt++; cnt--; q.push(s1); num.push(0); int ans = bfs(); if(ans == -1) { cout << "NO ANSWER!"; return 0; } else cout << ans; return 0; }