洛谷P1032 字串变换

url: https://www.luogu.com.cn/problem/P1032

tag:
NOIP2002 提高组,字符串,bfs

思路:
因为是求最少的变换次数,所以可以用bfs。每次搜索都遍历字符串的每一个位置,将可以替换的地方都替换,然后判断是否出现过,没有出现过就加入队列。最后第一次出现字符串b的时候步数就是答案。

代码:

  1. #include <iostream>
  2. #include <queue>
  3. #include <map>
  4. #include <unordered_set>
  5. using namespace std;
  6. typedef pair<string, string> PSS;
  7. typedef pair<string, int> PSI;
  8. PSS mp[6];
  9. string a, b;
  10. queue<PSI> q;
  11. unordered_set<string> st;
  12. int idx = 0;
  13. int bfs()
  14. {
  15. q.push({a, 0});
  16. st.insert(a);
  17. while (!q.empty())
  18. {
  19. auto [current, step] = q.front(); q.pop();
  20. if (current == b) return step;
  21. if (step >= 10) continue;
  22. for (int i = 0; i < idx; i++)
  23. {
  24. string from = mp[i].first;
  25. string to = mp[i].second;
  26. size_t pos = current.find(from);
  27. while (pos != string::npos)
  28. {
  29. string newstr = current.substr(0, pos) + to + current.substr(pos + from.size());
  30. if (newstr.size() <= 20)
  31. {
  32. if (!st.count(newstr))
  33. {
  34. st.insert(newstr);
  35. q.push({newstr, step + 1});
  36. }
  37. }
  38. pos = current.find(from, pos + 1);
  39. }
  40. }
  41. }
  42. return -1;
  43. }
  44. int main()
  45. {
  46. ios::sync_with_stdio(false);
  47. cin.tie(0);
  48. cin >> a >> b;
  49. string c, d;
  50. while (cin >> c >> d)
  51. {
  52. if (!c.empty() && idx < 6)
  53. {
  54. mp[idx++] = {c, d};
  55. }
  56. }
  57. int res = bfs();
  58. if (res != -1 && res <= 10)
  59. cout << res;
  60. else
  61. cout << "NO ANSWER!";
  62. return 0;
  63. }
添加新评论