zoukankan      html  css  js  c++  java
  • POJ 3278 Catch That Cow(简单BFS)

    题目链接:http://poj.org/problem?id=3278

    题目大意:给你两个数字n,k。可以对n执行操作(n+1,n-1,n*2),问最少需要几次操作使n变成k。

    解题思路:bfs,每次走出三步n-1,n+1,n*2入队,直到最后找到答案为止。要注意:

         ①n不能变为负数,负数无意义,且无法用数组记录状态会runtime error

         ②n不用大于100000

    代码:

     1 #include<cstdio>
     2 #include<cstring>
     3 #include<queue>
     4 using namespace std;
     5 const int N=1e5+5;
     6 
     7 int n,k;
     8 int vis[N];
     9 
    10 
    11 struct node{
    12     int val,step;
    13 }pre,now;
    14 
    15 int bfs(){
    16     queue<node>q;
    17     now.val=n;
    18     now.step=0;
    19     q.push(now);
    20     while(!q.empty()){
    21         pre=q.front();
    22         q.pop();
    23         for(int i=1;i<=3;i++){
    24             int t;
    25             if(i==1)
    26                 t=pre.val+1;
    27             if(i==2)
    28                 t=pre.val-1;
    29             if(i==3)
    30                 t=pre.val*2;
    31             if(t<0||t>N||vis[t])
    32                 continue;
    33             if(t==k)
    34                 return pre.step+1;
    35             vis[t]=1;
    36             now.val=t;
    37             now.step=pre.step+1;
    38             q.push(now);
    39         }
    40     }
    41     return 0;
    42 }
    43 
    44 int main(){
    45     while(~scanf("%d%d",&n,&k)){
    46         memset(vis,0,sizeof(vis));
    47         if(n==k)
    48             puts("0");
    49         else
    50             printf("%d
    ",bfs());
    51     }
    52 } 
  • 相关阅读:
    Java应用程序的运行机制
    IO流——字符流
    IO流——字节流
    Java API --- File类
    SSM框架整合
    Mybatis核心组件
    AJAX 练习
    设计者模式
    软件七大设计原则
    并发编程
  • 原文地址:https://www.cnblogs.com/fu3638/p/7509604.html
Copyright © 2011-2022 走看看