博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
九度 1482:玛雅人的密码(BFS)
阅读量:6916 次
发布时间:2019-06-27

本文共 1344 字,大约阅读时间需要 4 分钟。

题目描述:

玛雅人有一种密码,如果字符串中出现连续的2012四个数字就能解开密码。给一个长度为N的字符串,(2=<N<=13)该字符串中只含有0,1,2三种数字,问这个字符串要移位几次才能解开密码,每次只能移动相邻的两个数字。例如02120经过一次移位,可以得到20120,01220,02210,02102,其中20120符合要求,因此输出为1.如果无论移位多少次都解不开密码,输出-1。

 

思路

1. 朴素 BFS 可解

2. 看了下题目来源, 2012 清华机试, 唔, 模拟, 数学, 动规, 三题一个小时. 当你考清华一同学向我描述清华的的机试状况. 

 

代码

#include 
#include
#include
#include
#include
#include
using namespace std;string str;int N;bool visited[1600000];bool match(const string &str1) { for(int i = 0; i <= N-4; i ++) { if(str1.substr(i, 4) == "2012") return true; } return false;}int hash_func() { int res = 0; for(int i = 0; i < N; i ++) res = res*3+str[i]-'0'; return res;}int main() { while(scanf("%d", &N) != EOF) { cin >> str; memset(visited, 0, sizeof(visited)); deque
record; record.push_back(str); int cur_lel = 1, nxt_lel = 0, ret = 0; bool found = false; while(!record.empty()) { string cur = record.front(); record.pop_front(); cur_lel --; if(match(cur)) { found = true; cout << ret << endl; break; } for(int i = 0; i < N-1; i ++) { swap(str[i], str[i+1]); int hash_val = hash_func(); if(!visited[hash_val]) { visited[hash_val] = true; record.push_back(str); nxt_lel ++; } swap(str[i], str[i+1]); } if(cur_lel == 0) { cur_lel = nxt_lel; nxt_lel = 0; ret ++; } } if(!found) cout << -1 << endl; } return 0;}

 

转载地址:http://qsxcl.baihongyu.com/

你可能感兴趣的文章
Sencha touch 初体验
查看>>
锋利的jQuery-1--解决jquery库和其他库的冲突
查看>>
SSH框架
查看>>
第1章 游戏之乐——小飞的电梯调度算法
查看>>
Codeforces Round #256 (Div. 2) C. Painting Fence 或搜索DP
查看>>
component to string 自定义窗体
查看>>
Atitit.收银系统模块架构attilax 总结
查看>>
hibernate(十)双向关联关系的CRUD
查看>>
hadoop学习;大数据集在HDFS中存为单个文件;安装linux下eclipse出错解决;查看.class文件插件...
查看>>
SolrCloud-5.2.1 集群部署及测试
查看>>
手动搭建SpringMVC报错
查看>>
UNIX网络编程卷1 时间获取程序server UDP 协议无关
查看>>
CMSPRESS-PHP无限级分类
查看>>
Android Fragment 真正的完全解析(上)
查看>>
selinux开启关闭
查看>>
linux 编译ffmpeg 支持x264, x265
查看>>
输入子系统--event层分析【转】
查看>>
fragment生命周期
查看>>
在Windows Server 2012 中安装 .NET 3.5 Framework
查看>>
git 笔记
查看>>