POJ 3278 Catch That Cow(Pu1 2018.10.1)
阿新 • • 發佈:2018-12-13
演算法:bfs
難度:NOIP-
題意:從N走到K,
開始輸入N,K。
有三種移動方法:1、向前走一步,耗時一分鐘。
2、向後走一步,耗時一分鐘。
3、向前移動到當前位置的兩倍N*2,耗時一分鐘。
問從N到K的最少時間。
題解:從N開始bfs,直到K結束。一共有三種走法,列舉即可。
注意:因為地圖是線性,所以如果,輸出N-K即可。
其他情況去bfs
程式碼如下:
#include <cstdio> #include <iostream> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> #include <queue> #define ll long long #define N 100005 using namespace std; int vis[N],dis[N]; int ans=0x3f3f3f3f; int n,k; queue<int>Q; void dfs(int rt) { vis[rt]=1; Q.push(rt); while(!Q.empty()) { int u=Q.front(); Q.pop(); int to; for(int i = 1;i <= 3;i++) { if(i==1) to=u+1; else if(i==2) to=u-1; else if(i==3) to=u*2; if(to<0||to>N) continue; if(!vis[to]) { vis[to]=1; Q.push(to); dis[to]=dis[u]+1; } if(to==k) { ans=min(ans,dis[to]); } } } } int main() { scanf("%d%d",&n,&k); if(n>=k) { printf("%d\n",n-k); }else { dfs(n); printf("%d\n",ans); } return 0 ; }