标签:10 头牛 int 短路 long times 1100 push AcWing
带条件的 BFS 最短路
点击查看代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
int n, m;
int d[N];
int bfs(int x)
{
queue<int> q;
q.push(x);
memset(d, -1, sizeof d);
d[x] = 0;
while (q.size()) {
auto t = q.front();
q.pop();
if (t + 1 <= m && d[t + 1] == -1) {
d[t + 1] = d[t] + 1;
q.push(t + 1);
}
if (t - 1 >= 0 && d[t - 1] == -1) {
d[t - 1] = d[t] + 1;
q.push(t - 1);
}
if (t * 2 < N && d[t * 2] == -1) {
d[t * 2] = d[t] + 1;
q.push(t * 2);
}
if (d[m] != -1)
return d[m];
}
return -1;
}
void solve()
{
cin >> n >> m;
cout << bfs(n) << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}
- 对于一个数 \(t\),能走到的数包括三种情况:
① \(t + 1 \leqslant k\),当 \(t + 1 > k\) 时,每走一个 \((t + 1)\),就一定要走一个 \((t - 1)\),一定不是最短路
② \(t - 1 \geqslant 0\),当 \(t - 1 < 0\) 时,每走一个 \((t - 1)\),就一定要走一个 \((t + 1)\),一定不是最短路
③ \(2 \cdot t \leqslant MAX\),这里的 \(MAX\) 设置为 \(2 \times 10^{5}\),因为 \(k\) 最大为 \(10^{5}\),\(\times 2\) 这个操作最多到 \(2 \times 10^{5}\)
标签:10,头牛,int,短路,long,times,1100,push,AcWing 来源: https://www.cnblogs.com/wKingYu/p/16544932.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。