Problem #1888
你坐在陆行鸟上进行一个挖宝任务,陆行鸟有三种移动方式,假定移动前的坐标为 X,则:
1. 移动到 2X 的地方。
2. 移动到 X−1 的地方。
3. 移动到 X+1 的地方。
为了尽快挖到宝物而不至于被别人先挖到,你需要选择最快的方式挖到宝物。
题解:
1.这道题的tag是最短路径.....其实可以理解,每一个数字连3条边。比如10->11,10->9,10->20。然后跑一边SPFA就可以出答案了。。
2.但事实上呢觉得呢好像没什么必要,跑BFS似乎也是可以的,我写的题解是用BFS+A*,通过优先队列按照离答案的距离判断优先级,第一个出的答案就是了。
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <set>
#define INF 0x3f3f3f3f
using namespace std;
const int maxLength = 200000;
int Source;
int Target;
struct Point{
int step;
int x;
bool operator < (const Point& rhs) const{
if(x == Target)
return false;
if(step == rhs.step)
return abs(Target - x) > abs(Target - rhs.x);
return
step > rhs.step;
}
Point(int a = 0, int b = 0):x(a),step(b){};
};
int main(){
int ans = 0;
while(cin >> Source >> Target)
{
priority_queue<Point> Q;
set<int> Sets;
Q.push(Point(Source,0));
while(!Q.empty())
{
Point cur = Q.top(); Q.pop();
if(cur.x == Target)
{
ans = cur.step;
break;
}
int steps = cur.step + 1;
int v1 = cur.x * 2;
int v2 = cur.x + 1;
int v3 = cur.x - 1;
if(v1 < maxLength && v1 > -maxLength && Sets.count(v1) == 0)
{
Q.push(Point(v1,steps));
Sets.insert(v1);
}
if(v2 < maxLength && v2 > -maxLength && Sets.count(v2) == 0)
{
Q.push(Point(v2,steps));
Sets.insert(v2);
}
if(v3 < maxLength && v3 > -maxLength && Sets.count(v3) == 0)
{
Q.push(Point(v3,steps));
Sets.insert(v3);
}
}
cout << ans << endl;
}
return 0;
}