题目背景
本题疑似错题,不保证存在靠谱的多项式复杂度的做法。测试数据非常的水,各种做法都可以通过,不代表算法正确。因此本题题目和数据仅供参考。
题目描述
已知有两个字串 A,BA,B 及一组字串变换的规则(至多 66 个规则):
A_1\to B_1A1→B1
A_2\to B_2A2→B2
规则的含义为:在 AA 中的子串 A_1A1 可以变换为 B_1B1,A_2A2 可以变换为 B_2\cdotsB2⋯。
例如:A=\text{abcd}A=abcd,B=\text{xyz}B=xyz,
变换规则为:
\text{abc}\rightarrow\text{xu}abc→xu,\text{ud}\rightarrow\text{y}ud→y,\text{y}\rightarrow\text{yz}y→yz
则此时,AA 可以经过一系列的变换变为 BB,其变换的过程为:
\text{abcd}\rightarrow\text{xud}\rightarrow\text{xy}\rightarrow\text{xyz}abcd→xud→xy→xyz。
共进行了 33 次变换,使得 AA 变换为 BB。
输入格式
输入格式如下:
AA BB
A_1A1 B_1B1
A_2A2 B_2B2 |-> 变换规则
... .../
所有字符串长度的上限为 2020。
输出格式
若在 1010 步(包含 1010 步)以内能将 AA 变换为 BB,则输出最少的变换步数;否则输出 NO ANSWER!
输入输出样例
输入 #1复制
abcd xyz abc xu ud y y yz
输出 #1复制
3
说明/提示
【题目来源】
NOIP 2002 提高组第二题
上代码:
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
#include <map>
#define maxn 15
using namespace std;
struct node{//方便搜索,也可以使用pair简化
string str;
int step;
};
string a,b;
string orginal[maxn];
string translated[maxn];
int n,ans;
map<string,int> ma;//很重要的东西,用来判重,否则会TLE在第3点和第5点
string trans(const string &str,int i,int j){//借鉴了stdcall大爷的思想
string ans = "";
if (i+orginal[j].length() > str.length())
return ans;
for (int k=0; k < orginal[j].length();k++)
if (str[i+k] != orginal[j][k])
return ans;
ans = str.substr(0,i);
ans+=translated[j];
ans+=str.substr(i+orginal[j].length());
return ans;
}
void bfs(){//一个平淡无奇的bfs过程
queue <node> q;
node s;
s.str = a;
s.step = 0;
q.push(s);
while (!q.empty()){
node u = q.front();
q.pop();
string temp;
if(ma.count(u.str) == 1) //剪枝,判断重复的路径
continue;
if (u.str == b){
ans = u.step;
break;
}
ma[u.str] = 1;
for (int i=0;i < u.str.length();i++)//枚举当前串所有可能位置
for (int j=0; j<n; j++){//枚举所有可能手段
temp = trans(u.str,i,j);
if (temp != ""){
node v;
v.str = temp;
v.step = u.step+1;
q.push(v);
}
}
}
if (ans > 10 || ans == 0)
cout << "NO ANSWER!" << endl;
else
cout << ans << endl;
}
int main(){
cin >> a >> b;
while (cin >> orginal[n] >> translated[n])
n++;
bfs();
return 0;
}