洛谷 P1032 字串变换
题目:
- 有公式,转链接
题解:
- 坑点重重... ...
- 要用bfs (第一个搜到的就是答案,节约时间)
一个字符串可能对应着许多不同的字符串
- bfs模版里pop时vis数组也要相应的清零
- 用map去重
- 记得无解的情况
一个串中可能有多个可替换串
#include <iostream>
#include <cstdio>
#include <string>
#include <map>
#include <queue>
#include <cstdlib>
using namespace std;
struct Cha {string x, y;} cha[10];
struct Obj {string s; int step;};
int n;
string a, b;
map<string, string> mp;
map<string, bool> vis;
void bfs()
{
queue<Obj> que;
Obj tmp;
tmp.s = a, tmp.step = 0;
que.push(tmp), vis[a] = 1;
while(!que.empty())
{
Obj now = que.front(); que.pop();
for(int i = 1; i <= n; i++)
{
int last = 0;
while(1)
{
string t = cha[i].x;
int pos = now.s.find(t, last);
if(pos == -1) break;
else last = pos + 1;
tmp.s = now.s.substr(0, pos) + cha[i].y + now.s.substr(pos + t.size(), now.s.size() - (pos + t.size()));
tmp.step = now.step + 1;
if(tmp.step > 10) continue;
if(tmp.s == b) {cout << tmp.step; exit(0);}
if(!vis[tmp.s])
{
vis[tmp.s] = 1;
que.push(tmp);
}
}
}
}
}
int main()
{
freopen("P1032.in", "r", stdin);
freopen("P1032.out", "w", stdout);
cin >> a >> b;
while(cin >> cha[++n].x) cin >> cha[n].y;
bfs();
cout << "NO ANSWER!";
return 0;
}