密码锁
题目描述
玛雅人有一种密码,如果字符串中出现连续的2012四个数字就能解开密码。给一个长度为N的字符串(2=<N<=13),该字符串中只含有0,1,2三种数字,问这个字符串要移位几次才能解开密码,每次只能移动相邻的两个数字。例如02120经过一次移位,可以得到20120,01220,02210,02102,其中20120符合要求,因此输出为1.如果无论移位多少次都解不开密码,输出-1。
输入描述:
第一行输入N,第二行输入N个数字,只包含0,1,2
输出描述:
输出字符串要移几位才能解开密码,如果无论移位多少次都解不开密码,输出-1
示例1
输入
复制
5 02120 5 02120
输出
复制
1 1
代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
string s;
int t;
bool operator < (const node&st)const{
return t > st.t;
}
};
string str;
int BFS(){
priority_queue<node> q;
map<string, int> mp;
mp[str] = 1;
q.push({str, 0});
while(!q.empty()){
node now = q.top();
q.pop();
if(now.s.find("2012")!=string::npos){
return now.t;
}
for(int i=0; i<now.s.size()-1; i++){
swap(now.s[i], now.s[i+1]);
if(mp.count(now.s)){
swap(now.s[i], now.s[i+1]);
continue;
}
mp[now.s] = 1;
q.push({now.s, now.t+1});
swap(now.s[i], now.s[i+1]);
}
}
return -1;
}
int main()
{
int n;
while(scanf("%d", &n)!=EOF){
cin >> str;
printf("%d\n", BFS());
}
return 0;
}