原题:P1032
死因: TLE
怎么解决 TLE
?(难道真的只能用 string
吗?)
代码:
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
#include<cstring>
#include<map>
using namespace std;
char sta[25],goa[25],chg[7][2][25];
int cn,l[7][2];
map<vector<char>,bool>v;
struct str{
int st,l;
vector<char>x;
void csh(){
for(int i=1;i<=25;i++)x.push_back(' ');
}
}tmp,ch;
int main(){
tmp.csh();ch.csh();
scanf(" %s %s",sta+1,goa+1);
while(scanf(" %s %s",chg[cn+1][0]+1,chg[cn+1][1]+1))
cn++,l[cn][0]=strlen(chg[cn][0]+1),l[cn][1]=strlen(chg[cn][1]+1);
tmp.l=strlen(sta+1);
for(int i=1;i<=tmp.l;i++)tmp.x[i]=sta[i];
queue<str>q;
q.push(tmp);
v[tmp.x]=true;
while(!q.empty()){
tmp=q.front();
q.pop();
if(tmp.l==strlen(goa+1)){
bool pp=true;
for(int i=1;i<=tmp.l;i++)if(tmp.x[i]!=goa[i])pp=false;
if(pp){
printf("%d",tmp.st);
return 0;
}
}
ch.st=tmp.st+1;
for(int k=1;k<=cn;k++){
for(int i=1;i<=tmp.l-l[k][0]+1;i++)if(tmp.x[i]==chg[k][0][1]){
bool pp=true;
for(int j=i;j<=i+l[k][0]-1;j++)if(tmp.x[j]!=chg[k][0][j-i+1])pp=false;
if(pp){
ch.l=tmp.l-l[k][0]+l[k][1];
for(int j=1;j<i;j++)ch.x[j]=tmp.x[j];
for(int j=i;j<=i+l[k][1]-1;j++)ch.x[j]=chg[k][1][j-i+1];
for(int j=i+l[k][1];j<=ch.l;j++)ch.x[j]=tmp.x[j-l[k][1]+l[k][0]];
if(!v[ch.x]){
q.push(ch);
v[ch.x]=true;
}
}
}
}
}
printf("NO ANSWER!");
return 0;
}