宽度优先搜索 之 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; }
相关文章推荐
- Shell编程实例
- 随便写点时间相关的模块
- 因式分解 和 分式方程
- LAMP 1.2 Apache编译安装
- bps、pps、fps
- 二叉树的定义、性质
- iOS-网络处理
- Oracle Linux 7.2 安装
- linux:/etc/skel 文件夹
- 后台管理界面--导航栏设计
- 分布式数据库主键id生成策略
- SQLite数据库
- 黑马程序员__Java异常处理
- PHP基础--数据类型
- 自定义View之字母导航控件
- C#正则表达式Regex常用匹配
- JavaWeb学习总结(三)——Tomcat服务器学习和使用(二)
- swoole之代码热更新实现
- 今天写个alterview的事件
- (温故而知新)之Struts2(类型转化)