POJ 3278 Catch That Cow(图论:BFS)
来源:互联网 发布:大数据探索性分析 编辑:程序博客网 时间:2024/05/01 20:11
POJ 3278 Catch That Cow(图论:BFS)
http://poj.org/problem?id=3278
题意:
在一个数轴上,给你一个起始点和终点,问你从起点走到终点最少需要多少步.你可以单步走也可以double跳跃.
其中单步走指你当前位置在x上,那么你下一步可以走到x+1或x-1位置上。
double跳跃指,你当前位置在x上,那么你下一步可以走到2*x位置上。
分析:
典型的BFS,不过注意点的坐标范围是[0,100000].
当起点s在终点e右边时,直接输出s-e即可。
其他情况则需要BFS解决了。
AC代码:
#include<cstdio>#include<cstring>#include<algorithm>#include<queue>using namespace std;const int maxn=100000+5;int d[maxn],vis[maxn];queue<int> Q;void BFS(){ while(!Q.empty()) { int x=Q.front();Q.pop(); for(int dir=0;dir<3;dir++) { int nx; if(dir==0) nx=x-1; else if(dir==1) nx=x+1; else nx=x*2; if(nx>=0&&nx<=100000&&vis[nx]==0) { vis[nx]=1; d[nx]=1+d[x]; Q.push(nx); } } }}int main(){ int a,b; scanf("%d%d",&a,&b); if(a>=b)//终点在起点左边时 { printf("%d\n",a-b); return 0; } memset(vis,0,sizeof(vis)); vis[a]=1; d[a]=0; Q.push(a); BFS(); printf("%d\n",d[b]); return 0;}
第二遍AC代码:
#include<cstdio>#include<queue>#include<cstring>using namespace std;const int maxn=100000+5;int n,k;int dist[maxn];int BFS(){ queue<int> Q; Q.push(n); memset(dist,-1,sizeof(dist)); dist[n]=0; while(!Q.empty()) { int x = Q.front();Q.pop(); for(int dir=0;dir<3;dir++) { int nx; if(dir==0) nx = x-1; else if(dir==1) nx = x+1; else nx = x*2; if(nx>=0 && nx<=100000 && dist[nx]==-1) { dist[nx] = dist[x]+1; Q.push(nx); if(nx == k) return dist[nx]; } } } return -1;}int main(){ while(scanf("%d%d",&n,&k)==2) { if(n>=k) { printf("%d\n",n-k); continue; } int res = BFS(); printf("%d\n",res); } return 0;}
0 0
- POJ 3278 Catch That Cow(图论:BFS)
- poj 3278 Catch That Cow BFS
- poj 3278 Catch That Cow BFS
- POJ 3278 Catch That Cow BFS
- poj 3278 bfs(Catch That Cow)
- poj 3278 Catch That Cow(bfs)
- POJ 3278 Catch That Cow bfs
- POJ 3278 Catch That Cow 【bfs+队列】
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow(BFS)
- poj 3278 Catch That Cow bfs
- poj 3278 Catch That Cow (BFS剪枝)
- POJ 3278 Catch That Cow[BFS]
- Poj 3278 Catch That Cow 裸bfs
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- poj 3278 Catch That Cow 【BFS】
- POJ--3278:Catch That Cow (BFS)
- 优化MyEclipse 8.6.1的启动速度与运行速度
- test
- OpenCV 中 Kmeans 用法整理
- C++对C的加强 总结(4)
- 史上最通俗易懂的关于JavaScript 的 prototype、原型继承、this指针的讲解
- POJ 3278 Catch That Cow(图论:BFS)
- 如何在myeclipse中取消鼠标覆盖提示功能?
- Ubuntu14.04下maven建立java项目
- ADSTATS.SQL HANG AT DBMS_STATS.GATHER_SCHEMA_STATS. (文档 ID 466294.1)
- C++对C的加强 总结(5)
- 【存储管理】系统调用mmap()
- iPhone-获取网络数据或者路径的文件名以及后缀
- Spring MVC-自定义数据类型转换解决方案
- SVN的文件夹链接太强大了!(目录链接,目录映射,svn:externals)