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;
}