https://www.luogu.com.cn/problem/P1032?contestId=67264https://www.luogu.com.cn/problem/P1032?contestId=67264广搜+string的函数解题
这道题本地测试数据时要用Ctrl+Z+回车才可以出ans
str.subster(0,i) 从第0个字符开始一共截取i个字符。
str.subster(j) 从第j个字符开始一直截取到最后一个字符。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<queue>
using namespace std;
map<string,int>m;
string a,b;
string c[20],d[20];
int n,ans;
struct node
{
string str;
int sum;
};
queue<node>q;
string change(string str,int i,int j)
{
string t="";
if(i+c[j].length()>str.length()) return t;//串不用变的长度+需要变得长度>串原本的长度 则不能替换
for(int k=0;k<c[j].length();k++)// 检测能否替换
if(str[i+k]!=c[j][k])
return t;
t=str.substr(0,i);//串中不用变得部分
t+=d[j];//改变后的部分
t+=str.substr(i+c[j].length());//加上替换部分后面不用替换的部分
}
int main()
{
cin>>a>>b;
while(cin>>c[n]>>d[n]) n++; //转换规则输入
node s;
s.str=a;
s.sum=0;
q.push(s);//初始的串
while(!q.empty())
{
node x=q.front();
q.pop();
string temp;
if(m.count(x.str)==1) continue;//判重,如果该形式的字符串出现过一次就跳过
if(x.str==b)
{
ans=x.sum;//转换完成后记录次数
break;
}
m[x.str]=1;//标记
for(int i=0;i<x.str.length();i++)//从头枚举哪里可以替换
{
for(int j=0;j<n;j++)//枚举串的改变规则
{
temp=change(x.str,i,j);//替换
if(temp!="")// 如果可以替换
{
node y;
y.str=temp;
y.sum=x.sum+1;
q.push(y);//将替换过的串加入队列
}
}
}
}
if(ans>10||ans==0)
cout<<"NO ANSWER!";
else
cout<<ans<<endl;
return 0;
}