用map居然不会超时甚至还蛮快,map比我想象中牛逼好多

#include <cstdio>
#include <iostream>
#include <queue>
#include <algorithm> 
#include <string>
#include <cstring>
#include <map>

using namespace std;

map<string, int> m;

int BFS(string &s){
	queue<string> q;
	string &current = s;
	q.push(current);
	m.insert(make_pair(current, 0));
	while(current.find("2012") == string::npos && !q.empty()){
		q.pop();
		for(int i=0; i<s.size()-1; i++){
			swap(current[i], current[i+1]);
			if(!m.count(current)){
				q.push(current);
				m.insert(make_pair(current, 0));
				string tmp = current;
				swap(current[i], current[i+1]);
				m[tmp] = m[current]+1;
			}else{
				swap(current[i], current[i+1]);
			}
			
		}
		current = q.front();
	}
	if(q.empty()){
		return -1;
	}
	return m[current];
}

int main(){
	int n;
	string s;
	while(scanf("%d",&n) != EOF){
		cin >> s;
		printf("%d\n",BFS(s));
	}
	return 0;
}