题目1482:玛雅人的密码
时间限制:1 秒
内存限制:128 兆
特殊判题:否
提交:3904
解决:972
题目描述:
玛雅人有一种密码,如果字符串中出现连续的2012四个数字就能解开密码。给一个长度为N的字符串,(2=<N<=13)该字符串中只含有0,1,2三种数字,问这个字符串要移位几次才能解开密码,每次只能移动相邻的两个数字。例如02120经过一次移位,可以得到20120,01220,02210,02102,其中20120符合要求,因此输出为1.如果无论移位多少次都解不开密码,输出-1。
输入:
输入包含多组测试数据,每组测试数据由两行组成。
第一行为一个整数N,代表字符串的长度(2<=N<=13)。
第二行为一个仅由0、1、2组成的,长度为N的字符串。
输出:
对于每组测试数据,若可以解出密码,输出最少的移位次数;否则输出-1。
样例输入:
5
02120
样例输出:
1
来源:
总是栽在细节上!该打!!
// 玛雅人的密码.cpp : 定义控制台应用程序的入口点。
//
#include<queue>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#define hmaxn 2000003
#define maxn 2000000
using namespace std;
typedef char st[14];
st o ,qu[maxn];
int n,head[hmaxn],nxt[maxn],step[maxn];
void print(int pos) {
for (int i = 0; i < n; i++) {
cout << qu[pos][i];
}
cout <<" "<< pos << endl;
//cout << ":" << step[pos] << endl;
}
int Hash(st a) {
int h = 0;
for (int i = 0; i < n; i++) {
h = (h * 10 + a[i]) % hmaxn;
}
return h;
}
int same(st & a, st& b) {
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) {
return 0;
}
}
return 1;
}
int try_to_insert(int pos) {
int h = Hash(qu[pos]);
int u = head[h];
while (u) {
if (!memcmp(qu[pos],qu[u],sizeof(st))) {
return 0;
}
u = nxt[u];
}
nxt[pos] = head[h];
head[h] = pos;
return 1;
}
int test(int pos) {
for (int i = 0; i <= n-4; i++) {
if (qu[pos][i] == '2'&&qu[pos][i+1] == '0'&&qu[pos][i+2] == '1'&&qu[pos][i+3] == '2') {
return 1;
}
}
return 0;
}
int bfs() {
memset(head, 0, sizeof(head));
memset(nxt, 0, sizeof(nxt));
int front = 1, rear = 2,pos;
memcpy(qu[front], o, sizeof(o));
step[front] = 0;
while (front < rear) {
//print(front);
if (test(front)) {
//cout << rear << endl;
return step[front];
}
for (int i = 0; i < n; i++) {
if (i > 0) {
st & tp = qu[rear];
memcpy(tp, qu[front], sizeof(o));
int tp2 = tp[i];
tp[i] = tp[i - 1];
tp[i - 1] = tp2;
if (try_to_insert(rear)) {
step[rear] = step[front] + 1;
rear++;
}
}
if (i < n-1) {
st & tp = qu[rear];
memcpy(tp, qu[front], sizeof(o));
int tp2 = tp[i];
tp[i] = tp[i + 1];
tp[i + 1] = tp2;
if (try_to_insert(rear)) {
step[rear] = step[front] + 1;
rear++;
}
}
}
front++;
}
return 0;
}
int main()
{
while (~scanf("%d", &n)) {
scanf("%s", &o);
int c1=0, c2=0, c0=0;
for (int i = 0; i < n; i++) {
if (o[i] == '2') {
c2++;
}
else if (o[i] == '0') {
c0++;
}
else if (o[i] == '1') {
c1++;
}
}
if (c2 < 2 || c0 < 1 || c1 < 1) {
cout << "-1" << endl;
continue;
}
int ans = bfs();
cout << ans << endl;
}
return 0;
}