啦啦最近真的是做搜索,马上就要刷完kuangbin大佬这13道搜索啦哈哈哈,说说G题我自己的想法吧
题目链接:https://vjudge.net/contest/221801#problem/G
emmmm说实话本人英语渣,看到这个题这么长一开始畏惧得一p,不过好在死活把它读下来了,读完以后发现这道题就一个搜索嘛,emmm感觉dfs,bfs都行,记录当前步骤就行了,在下左后用到宽搜,就用一个结构体队列保存状态,即栈1,栈2,以及栈12,还有到当前状态的步数step。一开始想着这个长度没啥用,后来发现第二个test死循环退不出来,才想到应该这个长度和搜索次数有关,在搜索到一个极限步数以后还没找到匹配结果,后面的就是循环了,所以这时候就应该输出-1,并退出函数,至于这个极限步数,在下用的len,wa了,第二次尝试用len^2,ac了,第三次尝试2*len,ac了,于是在下大胆猜测极限就是2*len,哈哈由于在下愚钝并未证明,还请各位大佬说明一下这个极限步骤为啥就是2*len呢。
talk is cheap,show me the code
#include<iostream>
#include<ios>//关同步
#include<string>
#include<queue>
using namespace std;
struct node{
string s1,s2;
string q;
int step;
node(){}
node(string a,string w,string e,int s){
s1=a;
s2=w;
q=e;
step=s;
}
};
string t1,t2,Q;
int len;
void bfs();
int main(){
ios_base::sync_with_stdio(false);
cin.tie();
int t;
cin>>t;
for (int i=1;i<=t;i++){
cin>>len;
cin>>t1>>t2>>Q;
cout<<i<<" ";
bfs();
}
return 0;
}
void bfs(){
queue<node> que;
que.push(node(t1,t2,"",0));
while(!que.empty()){
node now=que.front();
que.pop();
if (now.q==Q){
cout<<now.step<<"\n";
return;
}
if (now.step>2*len){//极限步数,后面都是循环前2len步
cout<<-1<<"\n";
return;
}
string nowq,nows1,nows2;
for (int i=0;i<now.s1.length();i++){//构造s12栈
nowq+=now.s2[i];
nowq+=now.s1[i];
}
for (int i=0;i<now.s1.length();i++)///构造新的s1
nows1+=nowq[i];
for (int i=now.s2.length();i<nowq.length();i++)///构造新的s2
nows2+=nowq[i];
que.push(node(nows1,nows2,nowq,now.step+1));
}
return;
}