题目链接:
代码如下:
#include <bits/stdc++.h>
using namespace std;
map<string,int> maps; //存储对应字符串需要的移位次数
bool Satisfy(string str){ //判断是否满足解密条件
if(str.find("2012")!=string::npos){ //判断str中是否有“2012”这个串
return true;
}else{
return false;
}
}
string exchange(string str,int i,int j){ //交换字符串str两个位置的元素
string strTmp=str;
char c=strTmp[i];
strTmp[i]=strTmp[j];
strTmp[j]=c;
return strTmp;
}
int BFS(string str){
queue<string> myQueue;
myQueue.push(str);
maps.clear();//每次输入案例需清空maps
maps[str]=0;//原始字符串移位0次
while(!myQueue.empty()){
string strTmp=myQueue.front();
myQueue.pop();
if(Satisfy(strTmp)){
return maps[strTmp];
}
for(int i=1;i<strTmp.size();i++){
string newStr=exchange(strTmp,i-1,i);
if(maps.find(newStr)==maps.end()){//newStr未出现过
maps[newStr]=maps[strTmp]+1;//移位次数加1
myQueue.push(newStr);//新字符串压入队列
}
}
}
return -1;//遍历完所有可能仍没有找到符合条件的字符串
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
string str;
cin>>str;
printf("%d\n",BFS(str));
}
return 0;
}