POJ 3278 Catch That Cow (BFS)

来源:互联网 发布:山东体育网络电视 编辑:程序博客网 时间:2024/05/22 11:41


Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (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 orX + 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 andK
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.

大致题意:

给定两个整数n和k

通过 n+1或n-1 或n*2 这3种操作,使得n==k

输出最少的操作次数


注意的地方有二:

1、  由于用于广搜的 队列数组 和 标记数组  相当大,如果定义这两个数组时把它们扔到局部去,编译是可以的,但肯定执行不了,提交就等RE吧= =

大数组必须开为 全局 。。。常识常识。。。

2、  剪枝。直接广搜一样等着RE吧= =

不剪枝的同学试试输入n=0  k=100000。。。。。。铁定RE

怎么剪枝看我程序

 


#include<iostream>#include<cstring>#include<algorithm>#include<cmath>#include<queue>#include<cstdio>using namespace std;const int N = 1e5 + 10;int vis[N*2];struct P{int num,step;P(int num,int step):num(num),step(step){}};queue<P>que;int bfs(int n,int m){que.push(P(n,0));while(!que.empty()) {P p = que.front();que.pop();if(p.num==m) return p.step;if(p.num>0 && vis[p.num-1]==0) {vis[p.num-1]=1;que.push(P(p.num-1,p.step+1));} if(p.num<m && vis[p.num+1]==0) {vis[p.num+1]=1;que.push(P(p.num+1,p.step+1));}if(p.num<m && vis[p.num*2]==0) {vis[p.num*2]=1;que.push(P(p.num*2,p.step+1));}}return 0;}int main(){int n,m;while(scanf("%d%d",&n,&m)!=EOF) {memset(vis,0,sizeof(vis));while(!que.empty()) que.pop();int ans = bfs(n,m);printf("%d\n",ans);}return 0;}



0 0
原创粉丝点击