HDOJ-2717(POJ-3278) Catch That Cow

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12309    Accepted Submission(s): 3824


Problem 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 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.
 
介个题主要还是BFS,但是情况不同了,有一个无限TP的农夫(好扯淡)。
代码:
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring> 
#define M 100000+10
using namespace std;
struct node
{
	int x;
	int step;
};
queue<node> q;
int vis[M];
int n,k;
int bfs()
{
	node now,next;
	while(!q.empty())
		q.pop();
	now.x=n;
	now.step=0;
	vis[now.x]=1;
	q.push(now);
	while(!q.empty())
	{
		now=q.front();
		q.pop();
		next=now;
		for(int i=0;i<3;i++)
		{
			if(i==0) next.x=now.x+1;
			if(i==1) next.x=now.x-1;
			if(i==2) next.x=now.x*2;
			next.step=now.step+1;
			if(next.x==k) return next.step;
			if(next.x<0||next.x>M) continue;
			if(!vis[next.x])
			{
				vis[next.x]=1;
				q.push(next);
			}
		}
	}
}

int main()
{
	while(~scanf("%d%d",&n,&k))
	{
		memset(vis,0,sizeof(vis));
		if(n<k)
			printf("%d\n",bfs());
		if(n>=k)
			printf("%d\n",n-k);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/Poseidon__ming/article/details/52068507
今日推荐