版权声明:Andy https://blog.csdn.net/Alibaba_lhl/article/details/82048260
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is tomove along
the following path: 5-10-9-18-17, which takes 4 minutes.
Source::Click here
心情:今天就是暑期集训的倒数第二天了,听完SDP学长讲完课,感觉自己的某些内容一点也不扎实,所以就先对之前所学的东西进行一下复习和进阶吧,要多做难题呀!不能老是刷模板题目了!那就不啰嗦了,开始吧!
题意
起点位于N,终点位于K。你有三种移动方式①:x -> x-1 ②:x -> x+1 ③:x ->2*x。每移动一次需要花费一分钟。求从起点到终点最少需要花费多长时间。
思路
可以理解为数轴上的迷宫,题目已给定了如何走迷宫的方式,并且所求的是所花费的最短时间,也就是最少需要移动几次,也就就是最短路,所以就用bfs搜索就行了,不过要注意一下剪枝啊(很重要的,不然会TLE的),还有就是要注意不要忘了标记数组啊,不然会MLE。
AC Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <functional>
#include <algorithm>
#include <algorithm>
#define _USE_MATH_DEFINES
using namespace std;
typedef long long ll;
const int MAXN = (int)1e5+5;
bool vis[MAXN];
struct Data
{
int x, val;
friend bool operator < (Data a, Data b)
{
return a.val > b.val;
}
};
int bfs(int n, int k)
{
int ans = 0;
memset(vis,false,sizeof(vis));
Data st1,st2;
priority_queue<Data> qu;
st1.x = n, st1.val = 0;
qu.push(st1);
vis[n] = true;
while(!qu.empty())
{
st1 = qu.top();
qu.pop();
if(st1.x==k)
{
ans = st1.val;
break;
}
for(int i=1; i<=3; i++)
{
if(i==1) st2.x = st1.x + 1;
if(i==2) st2.x = st1.x - 1;
if(i==3) st2.x = st1.x * 2;
if(st2.x<=100000 && st2.x>=0 && !vis[st2.x])//剪枝
{
vis[st2.x] = true;
st2.val = st1.val + 1;
qu.push(st2);
}
}
}
cout<< ans << endl;
}
int main()
{
int N, K;
cin>> N >> K;
bfs(N,K);
return 0;
}