王道机试指南 例题9.1 Catch That Cow
题目:
题目大意:
算法及原理:
代码:
#include <queue>
#include <iostream>
using namespace std;
struct Status{
int n;//记录走到哪了
int t;//记录当前时间
Status(int n0,int t0):n(n0),t(t0) {};
};
int BFS(int n,int k){
Status st(n,0);//初始状态位于n处,时间为0
queue<Status> q;
q.push(st);//初始状态入队
while(q.empty()==0){
Status tmp=q.front();//取队头元素
if(tmp.n==k)//走到k处则结束循环
return tmp.t;
q.pop();//队头元素出队
for(int i=0;i<3;i++){//三种可能的状态依次入队
Status ns(tmp.n,tmp.t+1);
if(i==0) ns.n--;
else if(i==1) ns.n++;
else ns.n=ns.n*2;
q.push(ns);
}
}
return -1;
}
int main(){
int n,k;
while(cin>>n>>k){
int minu=BFS(n,k);
cout<<minu<<endl;
}
return 0;
}
运行结果:


