poj3278Catch That Cow(bfs)
2015-07-27 17:03
239 查看
题目
Catch That CowDescription
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
Source
USACO 2007 Open Silver
思路:
代码
#include<iostream> #include<fstream> #include<string> #include<algorithm> #include<math.h> #include<stack> #include<queue> #include<set> #include<map> #include<vector> #include<stdio.h> #include<stdlib.h> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> using namespace std; typedef long long LL; typedef long double real; typedef vector<int> VI; /************************************************************** Problem: poj3278Catch That Cow Ordering: bfs Thought: 针对三个可行的步骤分三方向搜索,记录步数 Result: Accepted ****************************************************************/ #define INF 0x3f3f3f3f #define MINN -0x3f3f3f3f #define MAXN 0x3f3f3f3f #define MOD 10007 #define NUM 1000002 int n,k; int step[NUM]; bool vis[NUM]; int head,next; queue<int> q; int bfs() { memset(step,0,sizeof(step)); memset(vis,false,sizeof(vis)); while(!q.empty()) q.pop(); head=n; q.push(head); step[head]=0; vis[head]=true; while(!q.empty()) { head=q.front();q.pop(); for(int i=0;i<3;i++) { if(i==0) next=head-1; else if(i==1) next=head+1; else next=head*2; if(next<0 || next>=NUM) continue; if(!vis[next]) { q.push(next); vis[next]=true; step[next]=step[head]+1; } if(next==k) return step[next]; } } } int main() { //freopen("poj.in","r",stdin); //freopen("out.out","w",stdout); while(scanf("%d%d",&n,&k)!=EOF) { if(n>k) printf("%d\n",n-k); else printf("%d\n",bfs()); } return 0; }
相关文章推荐
- POJ-2456 Aggressive cows
- GDB十分钟教程
- vs2010 mvc3安装时报错
- Android四大组件的作用
- poj3278Catch That Cow(bfs)
- 【转-listview】ListView工作原理完全解析
- 破解织梦的登录密码
- DE之争:intellij vs eclipse系
- 自动创建设备节点class_create 和device_create
- lsdk无线驱动与管理层的接口
- 【图论】【二分图匹配】[ZOJ 1002]Fire Net
- HDU5285.wyh2000 and pupil
- android的“播放引擎stagefright”中“OMX文件解码”
- 原地随机排列数组
- AngularJS学习笔记
- maya制作玻璃材质
- 聚类之详解FCM算法原理及应用
- hdu 2546 饭卡(01背包)
- Duanxx的STM32学习:NVIC操作
- grunt压缩多个js文件和css文件