Problem1896--字串变化代码

1896: 字串变化代码

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 152  Solved: 129
[Submit] [Status] [Web Board] [Creator:]

Description

#include<bits/stdc++.h>
using namespace std;
string a,b,a1[20],b1[20];
int len;
struct node
{
string s;
int sum;
};
queue<node> q;
map<string,int> mp;  //mp[abc] 
void bfs()
{
q.push(node{a,0});
while(!q.empty())
{
node temp=q.front();
if(temp.sum>10)
break;
if(temp.s==b)
{
cout<<temp.sum;
return;
}
int k=0;
for(int i=0;i<len;i++)
{
while(1) //注意一个字符串中有可能有多个相同的字串 
{
int m=temp.s.find(a1[i],k);
if(m==-1)
break;
string x=temp.s;
x.replace(m,a1[i].size(),b1[i]);
if(!mp[x])
{
q.push(node{x,temp.sum+1});
mp[x]=1;
}
k=m+a1[i].size();
}
k=0;
}
q.pop();
}
cout<<"NO ANSWER!";
}
int main() 
{
//freopen("P1126_8.in","r",stdin);
cin>>a>>b;
while(cin>>a1[len]>>b1[len]) //while(scanf("%s %s",&a1,&b1)!=EOF) 
len++;
bfs();
return 0;
}

Source/Category