本文主要是介绍POJ3278 Catch That Cow(BFS) 坑爹的RE,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K
Description
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?**
InputLine 1: Two space-separated integers: N and K
OutputLine 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input5 17
Sample Output4
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(0≤N≤100000)处开始,母牛在同一数轴上的点K(0≤K≤10000)。 农夫有两种交通方式:步行和传送。
农夫可以前(当前坐标+1)后(当前坐标-1)行走或者传送(当前坐标*2),每次移动消耗一个单位时间,问追上奶牛的最短时间。
简单的BFS题,但是有很多坑,一不小心就RE。
以下是代码实现。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
bool vis[100010];
int n,k;
struct node{
int x;
int time;
};
int bfs()
{ node q;
q.x=n;q.time=0;queue<node>p;p.push(q);vis[n]=1;
while(!p.empty())
{node tmp=p.front();p.pop();if(tmp.x==k)
{return tmp.time;
}for(int i=0;i<3;i++){ int xx;if(i==0)xx=tmp.x-1;else if(i==1)xx=tmp.x+1;elsexx=tmp.x*2;if(xx>100005|| xx<0 ) continue;//坑点,没有判断容易数组越界,若超过则进行下一次循环if(!vis[xx]){node nx;nx.x=xx;vis[xx]=1;nx.time=tmp.time+1;p.push(nx);}}}return -1;//这行不能丢,虽然题目没给出要求
}int main()
{memset(vis,0,sizeof(vis));scanf("%ld%ld",&n,&k);//使用%ldif(n>=k){printf("%d",n-k);//若农夫在奶牛前面,则直接回退}else{printf("%d",bfs());}return 0;
}
这篇关于POJ3278 Catch That Cow(BFS) 坑爹的RE的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!