http://ac.jobdu.com/problem.php?pid=1482
参考了 http://blog.csdn.net/thyftguhfyguj/article/details/8994521
#include <stdio.h>
#include <cstring>
#include <queue>
static bool visit[1600000];
typedef struct node{
char s[14];
int step;
} Node;
bool there2012(char s[]){
int len = (int) strlen(s);
bool found = false;
for (int i = 0; i < len-3; ++i) {
if(s[i] == '2' && s[i+1] == '0' && s[i+2] == '1' && s[i+3] == '2'){
found = true;
break;
}
}
return found;
}
int hashString(char s[]){
int hashcode = 0;
int len = (int) strlen(s);
for (int i = 0; i < len; ++i) {
hashcode*=3;
hashcode += s[i] - '0';
}
return hashcode;
}
int main(){
//freopen("in/1482.in","r",stdin);
int n,n0,n1,n2;
char s[14];
std::queue<Node> Q;
while(scanf("%d\n",&n)!=EOF){
scanf("%s",s);
while(!Q.empty()) Q.pop();
memset(visit,false,sizeof(visit));
n0 = n1 =n2 = 0;
for (int i = 0; i < n; ++i) {
if(s[i] == '0') n0++;
if(s[i] == '1') n1++;
if(s[i] == '2') n2++;
}
if(n0<1||n1<1||n2<2) {
printf("-1\n");
continue;
}
Node node;
strcpy(node.s,s),node.step = 0;
Q.push(node);
bool found = false;
int min_step = 0;
while(!Q.empty() && !found){
Node t = Q.front();
Q.pop();
if(visit[hashString(t.s)]) continue;
visit[hashString(t.s)] = true;
if(there2012(t.s) ){
found = true;
min_step = t.step;
break;
}
for (int i = 0; i < n-1; ++i) {
std::swap(t.s[i],t.s[i+1]);
Node newt;
strcpy(newt.s,t.s);
newt.step = t.step+1;
Q.push(newt);
std::swap(t.s[i],t.s[i+1]);
}
}
if(found) printf("%d\n",min_step);
else printf("-1\n");
}
return 0;
}