当时我们校内比赛 我一看就是一道搜索题 结果没认真看 用的DFS怎么查 也查不出来 课下用的BFS做出来的 (PS:以后一定要看清题 求得是 最短 最少 一定要用BFS 别用DFS)
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 135540 Accepted: 41919 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?
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 17Sample Output
4Hint
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.
#include<queue>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define M 1000100
int vis[M];
int n,k;
bool check(int x){
if(x<0 || x>M || vis[x])
return false;
return true;
}
struct node
{
int x;
int step;
// node(int xx,int ss){
// x=xx;
// step=ss;
// }
};
int bfs(int x)
{
queue<node> q;
vis[x]=1;
node a,b;
a.x=x;
a.step=0;
q.push(a);
while(!q.empty())
{
a = q.front();
q.pop();
if(a.x == k) return a.step;
b.step = 0;
b.x=a.x-1;
if(check(b.x) ){
vis[b.x]=1;
b.step =a.step+1;
q.push(b);
}
b.x=a.x+1;
if(check(b.x)){
vis[b.x]=1;
b.step =a.step+1;
q.push(b);
}
b.x=a.x*2;
if(check(b.x)){
vis[b.x]=1;
b.step =a.step+1;
q.push(b);
}
}
return -1;
}
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
memset(vis,0,sizeof(vis));
printf("%d\n",bfs(n));
}
return 0;
}
这道题写的我很气 明明 ‘queue<node> q;’ 可以写bfs函数上面 也可以写在bfs函数里面 可是hdu偏偏不行 必须写到bfs函数里面 要么就WA 我找了俩小时 提交了快20次 才知道我错哪儿了
but poj就行 (滑稽.jpg)