POJ-3278 Catch That Cow

 1 #include<iostream>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<cstdio>
 6 #include<queue>
 7 using namespace std;
 8 
 9 struct node{
10     int n,step;
11     node(){};
12     node(int n,int step){
13         this->n=n;
14         this->step=step;
15     }
16 };
17 
18 int bfs(int n,int k){
19     if(!k)
20         return n;
21     queue<node>q;
22     q.push(node(n,0));
23     bool vis[100005];
24     memset(vis,0,sizeof(vis));
25     vis[n]=1;
26     while(!q.empty()){
27         node t=q.front();q.pop();
28         if(t.n==k)
29             return t.step;
30         if(t.n>k){
31             if(!vis[t.n-1]&&t.n-1>=0){
32                 q.push(node(t.n-1,t.step+1));
33                 vis[t.n-1]=1;
34             }
35         }
36         else{
37             int a=t.n-1,b=t.n+1,c=t.n*2,step=t.step+1;
38             if(a>=0&&!vis[a]){
39                 q.push(node(a,step));
40                 vis[a]=1;
41             }
42             if(!vis[b]&&b<100005){
43                 q.push(node(b,step));
44                 vis[b]=1;
45             }
46             if(c<100005&&!vis[c]){
47                 q.push(node(c,step));
48                 vis[c]=1;
49             }
50         }
51     }
52 
53 }
54 
55 int main(){
56     int n,k;
57     while(cin>>n>>k){
58         cout<<bfs(n,k)<<endl;
59     }
60 }
原文地址:https://www.cnblogs.com/NWUACM/p/6419119.html