poj 3278 Catch That Cow(大概是很顯然的bfs了)
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 123882 Accepted: 38547 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 × Xin 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.
【題意】給出n和k,起點和終點的位置。每次移動需要1分鐘,每次移動的方式有3種,+1、-1、×2,範圍是0~100000,求最短需要用多長時間。
【分析】bfs。需要用一個vis陣列,來記錄該點是不是已經走過,避免重複。然後,向前或向後即±1存進一個數組裡,再討論×2。如果最初n和k相同的話,用時顯然為0了。
【程式碼】
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<queue>
using namespace std;
struct node{
int x,step;
};
const int maxn=1e5+10;
int vis[maxn];
int dir[5]={-1,1};
int bfs(int n,int k)
{
queue<node>q;
node n1,n2,n3;
n1.step=0,n1.x=n;
q.push(n1);
while(!q.empty())
{
n2=q.front();q.pop();
if(n2.x==k) return n2.step;
for(int i=0;i<2;i++)
{
n3.x=n2.x+dir[i];
n3.step=n2.step+1;
if(n3.x<0 || n3.x>100000)continue;//這裡是x,不要寫成step....
if(vis[n3.x])continue;
vis[n3.x]=1;
q.push(n3);
}
n3.x=n2.x*2;n3.step=n2.step+1;
if(n3.x<0 || n3.x>100000)continue;
if(vis[n3.x])continue;
vis[n3.x]=1;
q.push(n3);
}
return 0;
}
int main()
{
int n,k;
while(~scanf("%d%d",&n,&k))
{
if(n==k)
{
puts("0");
continue;
}
memset(vis,0,sizeof(vis));
printf("%d\n",bfs(n,k));
}
return 0;
}