#include <algorithm> #include <iostream> #include <queue> #include <string> #include <map> using namespace std; int n;//n字符串长度 map <string, int> inq; struct Node{ string str; int step; }; queue<Node> q; //判断字符串是否存在连续的2012 bool judge(string str){ return (str.find("2012") != -1); } int BFS(){ while(!q.empty()){ Node top = q.front(); q.pop(); for(int i = 0; i < n - 1; i++){ string Nowstr = top.str; int Nowstep = top.step; swap(Nowstr[i], Nowstr[i + 1]); if(inq[Nowstr] == 0){ inq[Nowstr] = 1; Node tmp; tmp.str = Nowstr, tmp.step = Nowstep + 1; if(judge(Nowstr)) return tmp.step; q.push(tmp); } } } return -1; } int main(){ string s; cin >> n >> s; if(judge(s)) {cout << 0 << endl; return 0;} Node tmp; tmp.str = s, tmp.step = 0; while(!q.empty()) q.pop(); q.push(tmp); inq[s] = 1; cout << BFS() << endl; return 0; }