1. 程式人生 > >Catch That Cow poj 4001(抓住那頭牛!) BFS(廣度優先搜尋)

Catch That Cow poj 4001(抓住那頭牛!) BFS(廣度優先搜尋)

題目連結

其實就是求最短路徑問題,採用BFS即可。
AC程式碼如下:

#include <iostream>
#include <queue>
using namespace std;
const int maxn=2e5+5;
bool vis[maxn];
struct cow{
    int pos;
    int step;
    cow(int xx,int s):pos(xx),step(s){};
};
void bfs(int n,int k)
{
    queue <cow> q;
    q.push(cow(
n,0)); vis[n]=1; //標記該點已經走過了 while(!q.empty()) { cow temp=q.front(); q.pop(); if(temp.pos==k){ //說明找到目標點了 cout<<temp.step<<endl; return ; } else //說明還沒有找到目標 { int x=temp.pos; if( x<k &&
!vis[x+1] && x+1<=maxn){ q.push(cow(x+1,temp.step+1)); vis[x+1]=!vis[x+1]; //進佇列順便標記該點 } if( x<k && !vis[2*x] && 2*x<=maxn){ q.push(cow(2*x,temp.step+1)); vis[2*x]=!vis[2*x]; } if( x-1>=
0 && !vis[x-1] ){ q.push(cow(x-1,temp.step+1)); vis[x-1]=!vis[x-1]; } } } } int main() { int n,k; cin>>n>>k; bfs(n,k); return 0; }