POJ 3278C - Catch That Cow【BFS】

农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不。最少要花多少时间才能抓住牛?

Input

一行: 以空格分隔的两个字母: N 和 K

Output

一行: 农夫抓住牛需要的最少时间,单位分钟

Sample Input

5 17

Sample Output

4

Hint

农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.

bfs

code:

扫描二维码关注公众号,回复: 2604596 查看本文章
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=1000000+20;
bool vis[maxn];
int ans=0;
struct node{
	int x;
	int step;
	friend bool operator < (node a,node b){
		return a.step>b.step;
	}
};
void bfs(int s,int e)
{
	priority_queue<node> que;//直接使用队列也可 但时间 ... 居然慢了300ms 我...
//	memset(vis,0,sizeof(vis));//在这里清空的话 RE 不懂 我...
//	queue<node> que;
	node d1,d2,d3;
	d1.x=s;
	d1.step=0;
	que.push(d1);
	vis[s]=1;
	while(!que.empty())
	{
		d2=que.top();
		que.pop();
		if(d2.x==e)
		{
			ans=d2.step;
			break;
		}
		for(int i=1;i<=3;i++)//san zhong qing kuang te pan
		{
			if(i==1) d3.x=d2.x-1;
			if(i==2) d3.x=d2.x+1;
			if(i==3) d3.x=d2.x*2;
			if(d3.x<0 || d3.x>=maxn || vis[d3.x]) continue;
			d3.step=d2.step+1;
			vis[d3.x]=1;
			que.push(d3);
		}
	}
}
int main()
{
	int n,m;
	cin>>n>>m;
	memset(vis,0,sizeof(vis));//在main函数清空 AC ...
	bfs(n,m);
	cout<<ans<<endl; 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41333844/article/details/81321266
今日推荐