【NOIP2002】【Luogu1032】字串变换
作者:互联网
problem
solution
codes
/思路就是对于每个状态下的字符串,枚举可以替换的部分替换作为下一个新的状态。 #include<iostream> #include<queue> #include<string> #include<map> using namespace std; int n = 1, flag; string a, b, ai[1010], bi[1010]; queue<string>q; map<string, int>ma;//map判重防MLE int main(){ cin>>a>>b; while(cin>>ai[n]>>bi[n])n++; q.push(a); ma[a] = 0; while(q.size()){ string t = q.front(); q.pop(); if(t == b){ flag = 1; break; } if(ma[t]>10)break; //如果没有这层循环的话,就只能找到第一个子串,后面的会被忽略,如abaaaba abcdaba for(int j = 0; j < t.size(); j++){ string nt = t.substr(j); for(int i = 1; i < n; i++){ int tt = nt.find(ai[i]); if(tt == string::npos)continue; tt += j; //边界条件调起来很麻烦,以及最后直接+j就好了 string ttt = t.substr(0,tt)+bi[i]+t.substr(tt+ai[i].size()); if(!ma.count(ttt)){ ma[ttt] = ma[t]+1; q.push(ttt); } } } } if(flag)cout<<ma[b]<<"\n"; else cout<<"NO ANSWER!\n"; return 0; }
#include<iostream> #include<string> #include<queue> #include<set> //set判重 #define maxn 1010 using namespace std; string ai[maxn],bi[maxn]; struct node{ string str; int st; node(string a, int b):str(a),st(b){} }; set<string>s; int ans; int main(){ string a, b; cin>>a>>b; int n = 1; while(cin>>ai[n]>>bi[n])n++; queue<node>q; q.push(node(a,0)); while(q.size()){ node t = q.front(); q.pop(); if(t.str == b){ ans = t.st; break;} if(t.st > 10){ ans = 20; break; } for(int j = 0; j < t.str.size(); j++){ string nt = t.str.substr(j); for(int i = 1; i < n; i++){ int tt = nt.find(ai[i]); if(tt==string::npos)continue; tt += j; string ttt = t.str.substr(0,tt)+bi[i]+t.str.substr(tt+ai[i].size()); if(!s.count(ttt)){ q.push(node(ttt,t.st+1)); s.insert(ttt); } } } } //如果<10就因为找不到出来也是不成立的, 即ans没有被赋过值的话 if(ans == 20 || ans == 0)cout<<"NO ANSWER!\n"; else cout<<ans<<"\n"; return 0; }
标签:Luogu1032,string,NOIP2002,int,tt,ttt,ai,字串,include 来源: https://www.cnblogs.com/gwj13114/p/15556004.html