Catch That Cow

题目链接:https://vjudge.net/contest/277958#problem/K

题目大意:直线上的两个坐标N和K,其中从N出发到达K,可以变换为+1、-1或者*2,每变换一次坐标,需要花费一分钟,求最短时间到达K。

代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<queue>
 5 using namespace std;
 6 const int maxn=100001;//此处范围得准确,如果小了会Wrong
 7 
 8 int vis[maxn],step[maxn];
 9 queue<int>que;
10 
11 int bfs(int N,int K)
12 {
13     int next,top;
14     que.push(N);//农夫所在初始点入队
15     vis[N]=true;//标记已被访问
16     step[N]=0;//步数初始为0
17     while(!que.empty()){//队列非空时,执行循环
18         top=que.front();//取出队首
19         que.pop();//弹出队首
20         for(int i=0;i<3;i++){
21             if(i==0) next=top-1;
22             else if(i==1) next=top+1;
23             else next=top*2;
24             if(next<0||next>=maxn) continue;//如已出界,则排除该情况
25             if(!vis[next]){//如果改点还未被访问过
26                 que.push(next);//入队
27                 step[next]=step[top]+1;//步数+1
28                 vis[next]=true;//标记已被访问过
29             }
30             if(next==K) return step[next];//当遍历到结果,返回步数
31         }
32     }
33 }
34 int main()
35 {
36     int N,K;
37     while(~scanf("%d%d",&N,&K)){
38         memset(step,0,sizeof(step));
39         memset(vis,false,sizeof(vis));
40         while(!que.empty()) que.pop();//注意调用前要先清空
41         if(N>=K) printf("%d\n",N-K);
42         else printf("%d\n",bfs(N,K));
43     }
44     return 0;
45 }
View Code

 

posted @ 2019-02-24 20:28  里昂静  阅读(860)  评论(0编辑  收藏  举报