poj3278

BFS,注意判断数组是否越界,注意处理n==k的情况

View Code
#include <iostream>
#include
<cstdlib>
#include
<cstring>
#include
<cstdio>
#include
<queue>
using namespace std;

#define maxn 100005

struct Item
{
int step, pos;
Item()
{
}
Item(
int s, int p) :
step(s), pos(p)
{
}
};

int visited[maxn];

int main()
{
int n, k;
//freopen("D:\\t.txt", "r", stdin);
scanf("%d%d", &n, &k);
if (n == k)
{
printf(
"0\n");
return 0;
}
memset(visited,
0, sizeof(visited));
queue
<Item> q;
q.push(Item(
0, n));
while (1)
{
Item temp;
temp
= q.front();
q.pop();
if (temp.pos * 2 < maxn && !visited[temp.pos * 2])
{
q.push(Item(temp.step
+ 1, temp.pos * 2));
visited[temp.pos
* 2] = true;
}
if (temp.pos + 1 < maxn && !visited[temp.pos + 1])
{
q.push(Item(temp.step
+ 1, temp.pos + 1));
visited[temp.pos
+ 1] = true;
}
if (temp.pos - 1 >= 0 && !visited[temp.pos - 1])
{
q.push(Item(temp.step
+ 1, temp.pos - 1));
visited[temp.pos
- 1] = true;
}
if (visited[k])
{
printf(
"%d\n", temp.step + 1);
return 0;
}
}
return 0;
}
原文地址:https://www.cnblogs.com/rainydays/p/1965364.html