POJ3278-bfs

1.题目链接。题目大意就是农夫抓牛,给农夫的初始坐标和牛的坐标,农夫的移动只能是按照这三种方式:假设x位当前农夫的位置,那么农夫的下一个位置只能是:x-1,x+1,2x。求农夫移动多少次才能够抓住牛。这是一个bfs的裸题,几乎大家学bfs都是从这个题开始的。就不再多解释了,自己研究代码吧。

#include"stdafx.h"
#include<iostream>
#include<stdio.h>
#include<cstdio>
#include<queue>
#pragma warning(disable:4996)
using namespace std;
const int N = 1000010;
int vis[N], step[N];
queue<int>q;
int  bfs(int n, int k)
{
	vis[n] = 1;
	int now, next;
	step[n] = 0;
	q.push(n);
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		for (int i = 0; i < 3; i++)
		{
			if (i == 0)next = now - 1;
			if (i == 1)next = now + 1;
			if (i == 2)next = now * 2;
			if (next<0 || next>N)continue;
			if (!vis[next])
			{
				vis[next] = 1;
				q.push(next);
				step[next] = step[now] + 1;
			}
			if (next == k)return step[next];
		}

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

猜你喜欢

转载自blog.csdn.net/weixin_41863129/article/details/85869775