1. 程式人生 > >POJ3278 Catch That Cow(BFS)

POJ3278 Catch That Cow(BFS)

AI bool ostream ios turn HA ext else CI

給定兩個整數n和k,通過 n+1或n-1 或n*2 這3種操作,使得n==k

輸出最少的操作次數

#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;

const int maxn=100001;

bool visit[maxn];
int step[maxn];
queue <int> q;

int bfs(int n,int k)
{
    int head,next;
    q.push(n);
    step[n]
=0; visit[n]=true; while(!q.empty()) { head=q.front(); q.pop(); for(int i=0;i<3;i++) { if(i==0) next=head-1; else if(i==1) next=head+1; else next=head*2; if(next<0||next>=maxn) continue; if(!visit[next]) { q.push(next); step[next]
=step[head]+1; visit[next]=true; } if(next==k) return step[next]; } } } int main() { int n,k; cin>>n>>k; cout<<bfs(n,k)<<endl; return 0; }

POJ3278 Catch That Cow(BFS)