pku 3278 Catch That Cow 简单BFS

pku 3278 Catch That Cow 简单BFS

 1 # include  < iostream >
 2 # include  < cstring >
 3 # include  < queue >
 4 # include  < algorithm >
 5 using   namespace  std;
 6 int  len[ 500001 ];
 7 queue < int > q;
 8 int  main()
 9 {
10    int n,k;
11    cin>>n>>k;
12    memset(len,-1,sizeof(len));
13    len[n]=0;
14    q.push(n);
15    while(!q.empty())
16    {
17      int top=q.front();
18      q.pop();
19      if(top==k)
20      {
21        cout<<len[k]<<endl;
22       // system("pause");
23        return 0;
24      }

25      if(top+1<=2*max(n,k)&&(len[top+1]==-1||len[top+1]>len[top]+1)) 
26      {
27              len[top+1]=len[top]+1;
28              q.push(top+1);
29      }

30      if(top-1>=0&&(len[top-1]==-1||len[top-1]>len[top]+1)) 
31      {
32              len[top-1]=len[top]+1;
33              q.push(top-1);
34      }

35      if(top<=max(n,k)&&(len[top*2]==-1||len[top*2]>len[top]+1))
36      {
37              len[top*2]=len[top]+1;
38              q.push(top*2);
39      }

40    }

41    return 0;
42}

43
44

你可能感兴趣的:(pku 3278 Catch That Cow 简单BFS)