九度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; }
相关文章推荐
- linux ubunu中安装mysql
- IOS应用之间的跳转和数据传
- 软件项目的开发步骤(图)
- HDU5325——DP+搜索——Crazy Bobo
- Atom飞行手册翻译: 2.1 Atom中的包
- Netty百万级推送服务设计要点
- Java NIO
- PB中字符编码转换
- Oracle 表id实现自增
- BIEE初次启动密码输入错误
- 【语言-C++】MD5加密算法 32bit 16bit 源码
- Unity5中Inspector界面上的AssetBundle值设定问题
- Https流程(简单认识)
- HDUOJ 1896(优先队列)
- 写在Demo战斗系统之前,先用原型工具做套UI第二篇-人物选择界面制作
- css文字样式
- Linux中用mdadm管理软件raid
- Power Network
- C++_子类与基类的构造函数问题
- poj 2151 概率dp