算法提高课-搜索-最短路模型-AcWing 1100. 抓住那头牛:bfs
生活随笔
收集整理的這篇文章主要介紹了
算法提高课-搜索-最短路模型-AcWing 1100. 抓住那头牛:bfs
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目分析
來源:acwing
分析:bfs求最短步數(shù),需要dist[]數(shù)組來記錄最短步數(shù)。
ac代碼
#include<bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, k; int q[N]; int dist[N];int bfs(){memset(dist, -1, sizeof dist);dist[n] = 0;q[0] = n; // 起點是nint hh = 0, tt = 0;while( hh <= tt){int t = q[hh ++];if( t == k) return dist[k];if(t + 1 < N && dist[t + 1] == -1){dist[t+1] = dist[t] +1;q[++ tt] = t +1;}if( t -1 >= 0 && dist[t -1] == -1){dist[t-1] = dist[t] + 1;q[++ tt] = t -1;}if( t * 2 < N && dist[t *2] == -1){dist[t*2] = dist[t] +1;q[++ tt] = t * 2; }}return -1; }int main(){cin >> n >> k;cout << bfs() << endl; }題目來源
https://www.acwing.com/problem/content/1102/
總結
以上是生活随笔為你收集整理的算法提高课-搜索-最短路模型-AcWing 1100. 抓住那头牛:bfs的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法提高课-搜索-最短路模型-AcWin
- 下一篇: 算法提高课-搜索-多源BFS-AcWin