玛雅人的密码
题目描述
玛雅人有一种密码,如果字符串中出现连续的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。
输入
02120
输出
1
写这道题的时候踩了个坑,字符指针问题,刚开始赋值是用的字符指针直接赋值的,看了好久才发现一直是一个数组,我根本没有交换数据。所以提醒大家使用指针时一定要注意。
以下是我的拙劣答案
#include<bits/stdc++.h>
using namespace std;
#include<string>
struct Status{
char *str;
int result;
Status(char *str,int result) : str(str), result(result){}
};
char temp;
int i;
bool visit[100000000];
bool cmp(char str[],int lenth){
int j;
for(j = 0;j < lenth - 1;j++){
if(str[j] == '2' && str[j + 1] == '0' && str[j + 2] == '1' && str[j + 3] == '2')
{
return true;
}
}
return false;
}
int BFS(char str[], int lenth){
queue<Status> myQueue;
myQueue.push(Status(strcpy((char*)malloc(14),str),0));
visit[atoi(str)] = true;
Status current = myQueue.front();
while(!myQueue.empty()){
current = myQueue.front();
myQueue.pop();
if(cmp(current.str, lenth)){
return current.result;
}
for(i = 0;i < lenth - 1;i++){
Status next(strcpy((char*)malloc(14),current.str), current.result + 1);
temp = next.str[i];
next.str[i] = next.str[i + 1];
next.str[i + 1] = temp;
if(visit[atoi(next.str)]){
continue;
}
myQueue.push(next);
visit[atoi(next.str)] = true;
}
}
return 0;
}
int main(){
char str[14];
int lenth;
cin >> str;
lenth = strlen(str);
memset(visit, false,sizeof(visit));
cout << BFS(str,lenth) << endl;
return 0;
}