题目:字串变换
思路:
bfs。
注意要单向存图…
最开始把图建成了无向边,TLE一个点80分,想了半天的优化才发现图存错了…
吐槽luogu神数据…
代码:
#include<bits/stdc++.h>
using namespace std;
struct Pair {
string x;
int y;
Pair(string xx,int yy) {
x=xx,y=yy;
}
};
string a,b;
map<string,vector<string> > mp;
queue<Pair> que;
map<string,bool> cnt;
int bfs() {
que.push(Pair(a,0));
cnt[a]=true;
while(!que.empty()) {
Pair h=que.front();
que.pop();
for(int s=0; s<h.x.size(); s++) {
for(int t=s; t<h.x.size(); t++) {
string x=h.x.substr(s,t-s+1);
string frt=h.x.substr(0,s);
string bck=h.x.substr(t+1,h.x.size()-t-1);
for(int i=0; i<mp[x].size(); i++) {
string y=frt+mp[x][i]+bck;
if(cnt.count(y)) continue;
cnt[y]=1;
if(h.y==10) return -1;
if(y==b) return h.y+1;
que.push(Pair(y,h.y+1));
}
}
}
}
return -1;
}
int main() {
cin>>a>>b;
string x,y;
while(cin>>x>>y) {
mp[x].push_back(y);
}
int ans=bfs();
if(-1==ans) {
printf("NO ANSWER!");
return 0;
}
printf("%d",ans);
return 0;
}