题目:http://poj.org/problem?id=3278
在一条水平线上,起点为n,终点为k,移动1次耗时1分钟,只有三种移动方式:
1.向左移动1个单位
2.向右移动1个单位
3.传送到当前坐标值的2倍的位置
BFS
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5 + 7;
int n, k; // 起点,终点
int Min = INF;
int book[MAXN];
struct node
{
int pos, tim;
};
int bfs()
{
queue<node> q;
node start;
start.pos = n;
start.tim = 0;
q.push(start);
while(!q.empty())
{
node now = q.front(); q.pop();
if(now.pos == k) return now.tim;
node nxt;
if(now.pos - 1 >= 0 && !book[now.pos - 1])
{
book[now.pos - 1] = 1;
nxt.pos = now.pos - 1;
nxt.tim = now.tim + 1;
q.push(nxt);
}
if(now.pos + 1 <= 100000 && !book[now.pos + 1])
{
book[now.pos+ 1] = 1;
nxt.pos = now.pos + 1;
nxt.tim = now.tim + 1;
q.push(nxt);
}
if(now.pos * 2 <= 100000 && !book[now.pos* 2])
{
book[now.pos* 2] = 1;
nxt.pos = now.pos*2;
nxt.tim = now.tim + 1;
q.push(nxt);
}
}
}
int main()
{
cin >> n >> k;
memset(book, 0, sizeof(book));
book[n] = 1;
Min = bfs();
cout << Min << endl;
return 0;
}