Hdu 1195 Open the Lock
来源:互联网 发布:sql查询表语句怎么写 编辑:程序博客网 时间:2024/05/29 02:45
题目大意:有一个紧急开启密码锁的任务。密码由四位数字组成;每个数字从1到9;每次,可以对某一个数字进行加1或者减1;当从1加到9时,由9再加1会变为1;当从9减到1时,由1再减1会变为9;也可以交换两个相邻的数字,每次操作作为一个step。你的任务就是用最少的步骤解锁!
直接BFS即可
#include <cstdio>#include <iostream>#include <cstring>#include <string>#include <cstdlib>#include <algorithm>#include <cmath>#include <vector>#include <set>#include <list>#include <queue>#include <map>using namespace std;#define L(i) i<<1#define R(i) i<<1|1#define INF 0x3f3f3f3f#define pi acos(-1.0)#define eps 1e-4#define maxn 100010#define MOD 1000000007int first,last,a[4],b[4];int flag[10000];void BFS(){ queue<pair<int,int> > q; q.push(make_pair(first,0)); flag[first]++; while(!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); //printf("%d %d\n",x,y); if(x == last) { printf("%d\n",y); return; } for(int i = 3; i >= 0; i--) { a[i] = x % 10; x /= 10; } for(int i = 0; i < 4; i++) { int k = 0; a[i]++; if(a[i] == 10) a[i] = 1; for(int j = 0; j < 4; j++) k = k * 10 + a[j]; a[i]--; if(a[i] == 0) a[i] = 9; if(!flag[k]) { flag[k]++; q.push(make_pair(k,y+1)); } k = 0; a[i]--; if(a[i] == 0) a[i] = 9; for(int j = 0; j < 4; j++) k = k * 10 + a[j]; a[i]++; if(a[i] == 10) a[i] = 1; if(!flag[k]) { flag[k]++; q.push(make_pair(k,y+1)); } } for(int i = 0; i < 3; i++) { swap(a[i],a[i+1]); int k = 0; for(int j = 0; j < 4; j++) k = k * 10 + a[j]; swap(a[i],a[i+1]); if(!flag[k]) { flag[k]++; q.push(make_pair(k,y+1)); } } }}int main(){ int n,t; scanf("%d",&t); while(t--) { scanf("%d%d",&first,&last); memset(flag,0,sizeof(flag)); BFS(); } return 0;}
0 0
- HDU-1195-Open the Lock
- HDU 1195 Open the Lock
- HDU 1195 OPEN THE LOCK
- HDU-Open the Lock-1195
- hdu 1195 Open the Lock
- hdu-1195-Open the Lock
- HDU 1195 Open the Lock
- hdu 1195 Open the Lock
- HDU 1195 Open the Lock
- hdu(1195) Open the Lock
- HDU 1195 Open the Lock
- hdu 1195 Open the Lock
- HDU 1195 Open the Lock
- HDU 1195 Open the Lock
- HDU 1195 Open the Lock
- HDU - 1195 Open the Lock
- hdu 1195 Open the Lock
- HDU 1195 Open the Lock
- 《TCP/IP详解 卷1:协议》 读书笔记 第十一章 UDP:用户数据报协议
- Linux 内核 虚拟地址 物理地址 转换
- VS2012下X64平台嵌入汇编程序
- Android优化(二)——代码优化
- UGUI - 长按事件实现
- Hdu 1195 Open the Lock
- 每个android开发者都应该知道的Top 5三方库(2015版)
- java线程学习
- java内部类之方法内部类
- C语言的printf函数的执行顺序
- 单例设计模式
- scanf/fscanf 的%[]和%n使用方法 http://blog.csdn.net/wesweeky/article/details/6439777
- 解一元三次方程
- spi子系统的理解