您的位置:首页 > 其它

宽度优先搜索 之 CODE[VS] 1099 字串变换 2002年NOIP全国联赛提高组

2015-12-04 00:54 477 查看
/*
读懂题意,bfs即可AC。
关键考虑好,进入队列的是谁。
注意:
在实现的时候,调用std::string::operator+()和string.substr()很多次,会直接导致TLE。。
相同思路,换种实现(考虑使用string.replace()和string.find()),即可AC。
*/


#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstddef>
#include <iterator>
#include <algorithm>
#include <string>
#include <locale>
#include <cmath>
#include <vector>
#include <cstring>
#include <map>
#include <utility>
#include <queue>
#include <stack>
#include <set>
using namespace std;
const int INF = -0x3f3f3f3f;
const int MaxN = 55;
const int modPrime = 3046721;

struct Node
{
string str;
int stepCnt;
};

Node startOff;
string A, B;
vector<pair<string, string> > vecStr;
set<string> setStr;

void Solve()
{
queue<Node> queNode;
queNode.push(startOff);
while (!queNode.empty())
{
Node node = queNode.front();
queNode.pop();
string str = node.str;
int stepCnt = node.stepCnt;
if (node.str == B)
{
cout << stepCnt << endl;
return;
}
if (stepCnt == 10)
{
continue;
}

setStr.insert(str);
for (int i = 0; i < vecStr.size(); ++i)
{
for (int j = 0; j < str.size(); ++j)
{
int pos = str.find(vecStr[i].first, j);
if (pos != string::npos)
{
node.str = str;
node.str.replace(pos, vecStr[i].first.size(), vecStr[i].second);
if (setStr.find(node.str) == setStr.end())
{
node.stepCnt = stepCnt + 1;
queNode.push(node);
setStr.insert(node.str);
}
}
}
}
}
cout << "NO ANSWER!" << endl;
}

int main()
{
#ifdef HOME
freopen("in", "r", stdin);
//freopen("out", "w", stdout);
#endif

cin >> A >> B;
startOff.str = A;
startOff.stepCnt = 0;
string str1, str2;
while (cin >> str1 >> str2)
{
vecStr.push_back(make_pair(str1, str2));
}
Solve();

#ifdef HOME
cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
_CrtDumpMemoryLeaks();
#endif
return 0;
}






                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: