poj 3278 Catch That Cow

http://162.105.81.212/JudgeOnline/problem?id=3278

 

 

先构图, 这里用一个数组表示,

数组的值表示从N走到这里所需的最少步数,初始为-1

然后bfs, 每一步只能(-1,+1,*2)

#include<iostream> #include<queue> using namespace std; #define MAXSIZE 100001 int main() { int N,K,tmp,step,a[MAXSIZE]; while(scanf("%d%d",&N,&K)!=EOF) { memset(a, -1, sizeof(a)); queue<int> q; q.push(N); a[N]=0; //bfs while(!q.empty()) { step=q.front(); q.pop(); tmp=step-1; if(tmp>=0 && a[tmp]==-1) { a[tmp]=a[step]+1; q.push(tmp); if(tmp==K) break; } tmp=step+1; if(tmp<MAXSIZE && a[tmp]==-1) { a[tmp]=a[step]+1; q.push(tmp); if(tmp==K) break; } tmp=step<<1; if(tmp<MAXSIZE && a[tmp]==-1) { a[tmp]=a[step]+1; q.push(tmp); if(tmp==K) break; } } printf("%d/n",a[K]); } return 0; }

 

你可能感兴趣的:(poj 3278 Catch That Cow)