您的位置:首页 > 其它

九度OJ 玛雅人的密码

2015-07-29 13:57 369 查看

玛雅人的密码

玛雅人有一种密码,如果字符串中出现连续的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

思路:简单的状态搜索,用map记录字符串的状态加上常规的bfs即可。
我开始以为map<string,bool>效率会很低,然而也AC了。。。郁闷。。。
用map<char *,bool>就是要注意记得加上cmp,不然就是比较指针不是比较字符串了,要详细的话这里你们不妨看看map讲解
最后就是字符串长度小于4的时候直接返回-1额。

AC代码
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<map>
#include<queue>
using namespace std;
struct cmp
{
bool operator()( const char * s1, const char * s2 ) const
{
return strcmp( s1, s2 ) < 0;
}
};
struct Node{
char * s;
int step;
};
map<char *,bool,cmp> m;
queue<Node> q;
char s[15];
int n;
bool pass(Node now)
{
int len=strlen(now.s);
for(int i =0;i<len-3;++i){
if(now.s[i]=='2'&&now.s[i+1]=='0'&&now.s[i+2]=='1'&&now.s[i+3]=='2') return true;
}
return false;
}
void swap(char * s,int i)
{
char c=s[i];
s[i]=s[i+1];
s[i+1]=c;
}
void bfs()
{
m.clear();
m[s]=true;
while(!q.empty()) q.pop();
Node now;
now.s = s;
now.step = 0;
q.push(now);
while(!q.empty()){
now = q.front();
if(pass(now)){
printf("%d\n",now.step);
return ;
}
for(int i=0;i<n-1;++i){
char * tmp = new char [n+1];
for(int j=0;j<n;j++) tmp[j]=now.s[j];
swap(tmp,i);
if(!m[tmp]){
m[tmp]=true;
Node next;
next.s=tmp;
next.step=now.step+1;
q.push(next);
}else delete tmp;
}
q.pop();
}
printf("-1\n");
}
int main()
{
while(scanf("%d",&n)!=EOF){
scanf("%s",s);
if(strlen(s)<4) printf("-1\n");
else bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: