HDU1195Open the Lock( BFS )
来源:互联网 发布:淘宝买家秀暴露狂女 编辑:程序博客网 时间:2024/06/06 02:36
题意:开锁,给出了密码的初始状态,和目标状态,这里密码是固定的四位,每次可以把某一位加一或者减一,再者交换相邻的两位,最左边与最右边是不相邻的
解法:BFS,实现操作的函数即可
解法:BFS,实现操作的函数即可
#include<iostream>#include<cstdlib>#include<cmath>#include<algorithm>#include<cstring>#include<cstdio>#include<queue>#include<set>#include<stack>#define cl(a,b) memset(a,b,sizeof(a));#define LL long long#define P pair<int,int>#define X first#define Y second#define pb push_back#define out(x) cout<<x<<endl;using namespace std;const int maxn=9999+10;const int inf=9999999;int init,target;int change(int num,int pos,int kind){ int tmp[4]; int i=0; while(num){ tmp[i++]=num%10; num/=10; } reverse(tmp,tmp+4); if(kind==1){///add tmp[pos]++; if(tmp[pos]==10){ tmp[pos]=1; } } else { tmp[pos]--; if(tmp[pos]==0){ tmp[pos]=9; } } return tmp[0]*1000+tmp[1]*100+tmp[2]*10+tmp[3];}int swapnum(int num,int a,int b){ int tmp[4]; int i=0; while(num){ tmp[i++]=num%10; num/=10; } reverse(tmp,tmp+4); swap(tmp[a],tmp[b]); return tmp[0]*1000+tmp[1]*100+tmp[2]*10+tmp[3];}bool vis[maxn];int step[maxn];int bfs(){ cl(vis,false); cl(step,0); queue<int> q; q.push(init); vis[init]=true; while(!q.empty()){ int tmp=q.front();q.pop(); if(tmp==target){ return step[tmp]; } for(int i=0;i<=3;i++){///add int x=change(tmp,i,1); if(!vis[x]){ vis[x]=true; step[x]=step[tmp]+1; q.push(x); } } for(int i=0;i<=3;i++){ int x=change(tmp,i,0); if(!vis[x]){ vis[x]=true; step[x]=step[tmp]+1; q.push(x); } } for(int i=0;i<3;i++){ int x=swapnum(tmp,i,i+1); if(!vis[x]){ vis[x]=true; step[x]=step[tmp]+1; q.push(x); } } } return -1;}int main(){ int T; scanf("%d",&T); while(T--){ scanf("%d%d",&init,&target); printf("%d\n",bfs()); } return 0;}
0 0
- HDU1195Open the Lock(BFS)
- HDU1195Open the Lock( BFS )
- hdu1195Open the Lock(BFS)
- hdu1195Open the Lock(双向bfs+循环队列)
- HDU1195Open the Lock(AC)
- hdu1195Open the Lock
- hdu1195Open the Lock
- hdu1195Open the Lock(隐式图的广搜)
- Bfs++ open the lock
- Open the Lock(bfs)
- hdu1195 Open the Lock(BFS)
- HDU1195:Open the Lock(BFS)
- HDU1195:Open the Lock(BFS)
- hdu1195 Open the Lock (BFS)
- Open the Lock (BFS)
- zoj 2416 Open the Lock(BFS~)
- hdu 1195 Open the Lock bfs
- HDU 1195 Open the Lock BFS
- scala 第77讲:模式匹配下的提取器动手构造实战
- 向整包努力!!!
- 微信开发 文档集合 (链接)
- 排序算法的C语言实现-希尔排序
- 通达OA表单动态加载下拉菜单数据项
- HDU1195Open the Lock( BFS )
- DOS常用命令
- Spring @Configuration用annotation装配spring
- j2e中servlet转发action出现错误但是转发jsp可以
- 九度OJ 题目1004:Median
- HDU 1172.猜数字【思路转换,思维练习】【枚举】【8月8】
- 关于取出一个字符串中字母个数的题目分析
- linux /proc详解
- 在windows7上安装使用opengrok