宽度优先搜索 之 CODE[VS] 1099 字串变换 2002年NOIP全国联赛提高组
/*
读懂题意,bfs即可AC。
关键考虑好,进入队列的是谁。
注意:
在实现的时候,调用std::string::operator+()和string.substr()很多次,会直接导致TLE。。
相同思路,换种实现(考虑使用string.replace()和string.find()),即可AC。
*/
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstdio> 4 #include <cstddef> 5 #include <iterator> 6 #include <algorithm> 7 #include <string> 8 #include <locale> 9 #include <cmath> 10 #include <vector> 11 #include <cstring> 12 #include <map> 13 #include <utility> 14 #include <queue> 15 #include <stack> 16 #include <set> 17 using namespace std; 18 const int INF = -0x3f3f3f3f; 19 const int MaxN = 55; 20 const int modPrime = 3046721; 21 22 struct Node 23 { 24 string str; 25 int stepCnt; 26 }; 27 28 Node startOff; 29 string A, B; 30 vector<pair<string, string> > vecStr; 31 set<string> setStr; 32 33 34 void Solve() 35 { 36 queue<Node> queNode; 37 queNode.push(startOff); 38 while (!queNode.empty()) 39 { 40 Node node = queNode.front(); 41 queNode.pop(); 42 string str = node.str; 43 int stepCnt = node.stepCnt; 44 if (node.str == B) 45 { 46 cout << stepCnt << endl; 47 return; 48 } 49 if (stepCnt == 10) 50 { 51 continue; 52 } 53 54 setStr.insert(str); 55 for (int i = 0; i < vecStr.size(); ++i) 56 { 57 for (int j = 0; j < str.size(); ++j) 58 { 59 int pos = str.find(vecStr[i].first, j); 60 if (pos != string::npos) 61 { 62 node.str = str; 63 node.str.replace(pos, vecStr[i].first.size(), vecStr[i].second); 64 if (setStr.find(node.str) == setStr.end()) 65 { 66 node.stepCnt = stepCnt + 1; 67 queNode.push(node); 68 setStr.insert(node.str); 69 } 70 } 71 } 72 } 73 } 74 cout << "NO ANSWER!" << endl; 75 } 76 77 78 int main() 79 { 80 #ifdef HOME 81 freopen("in", "r", stdin); 82 //freopen("out", "w", stdout); 83 #endif 84 85 cin >> A >> B; 86 startOff.str = A; 87 startOff.stepCnt = 0; 88 string str1, str2; 89 while (cin >> str1 >> str2) 90 { 91 vecStr.push_back(make_pair(str1, str2)); 92 } 93 Solve(); 94 95 96 #ifdef HOME 97 cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl; 98 _CrtDumpMemoryLeaks(); 99 #endif 100 return 0; 101 }