zoukankan      html  css  js  c++  java
  • Catch That Cow(bfs)

    Description

    Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

    * Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
    * Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

    If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

    Input

    Line 1: Two space-separated integers: N and K

    Output

    Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

    Sample Input

    5 17

    Sample Output

    4
    此题需要注意的是queue应该定义全局,这一点上我wa了好几发
     1 #include <iostream>
     2 #include<stdio.h>
     3 #include<string.h>
     4 #include<queue>
     5 #include<vector>
     6 #include<algorithm>
     7 using namespace std;
     8 struct node
     9 {
    10     int cur,step;
    11 }st;
    12 queue<node>q;
    13 int m,n,ans,visit[200000];
    14 int dfs(int x)
    15 {
    16     int i;
    17     while(!q.empty())
    18     {
    19         q.pop();
    20     }
    21     memset(visit,0,sizeof(visit));
    22     node s,p;
    23     q.push(st);
    24     visit[st.cur]=1;
    25     while(!q.empty())
    26     {
    27         p=q.front();
    28         q.pop();
    29         if(p.cur==n)
    30             return p.step;
    31         for(i=1;i<=3;i++)
    32         {
    33             s=p;
    34             if(i==1)
    35                s.cur-=1;
    36             else if(i==2)
    37                 s.cur+=1;
    38             else
    39                 s.cur*=2;
    40             s.step++;
    41             if(s.cur==n)
    42                 return s.step;
    43             if(s.cur>=0&&s.cur<=200000&&!visit[s.cur])
    44             {
    45                 visit[s.cur]=1;
    46                 q.push(s);
    47             }
    48 
    49         }
    50     }
    51 
    52 }
    53 int main()
    54 {
    55     while(scanf("%d%d",&m,&n)!=-1)
    56     {
    57         st.cur=m;
    58         st.step=0;
    59         ans=dfs(m);
    60         printf("%d
    ",ans);
    61     }
    62     return 0;
    63 }
  • 相关阅读:
    什么是评审
    缺陷识别与缺陷跟踪
    白盒测试用例设计
    黑盒测试用例设计(二)
    黑盒测试用例设计技术
    Mysql基础
    JS函数
    SpringBoot整合JPA
    Python中的保留字
    操作系统的发展史
  • 原文地址:https://www.cnblogs.com/moomcake/p/8834445.html
Copyright © 2011-2022 走看看