题解 | #玛雅人的密码#
#include <iostream>
#include <queue>
#include <string>
using namespace std;
typedef pair<int, string> PII;
void DFS(string str){
queue<PII> q;
q.push({0, str});
while(!q.empty()){
auto t = q.front();
q.pop();
if (t.second.find("2012") != string::npos) {
cout << t.first << endl;
return;
}
for(int i = 0; i < t.second.length() - 1; i ++){
swap(t.second[i], t.second[i+1]);
q.push({t.first + 1, t.second});
swap(t.second[i], t.second[i+1]);//恢复交换前的字符串,对后续字符进行交换
}
}
cout << -1 << endl;
}
int main() {
int n;
string str;
while(cin >> n >> str){
DFS(str);
}
return 0;
}