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

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

    题意:

    给定两个整数n和k

    通过 n+1或n-1 或n*2 这3种操作,使得n==k

    输出最少的操作次数

     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<queue>
     4 using namespace std;
     5 int vis[200001];
     6 struct node
     7 {
     8    int x,step;
     9 };
    10 int bfs(int n,int k)
    11 {
    12     if(n==k)
    13     return 0;
    14     queue<node>q;
    15     struct node next,pos;
    16     next.step=0; next.x=n;
    17     vis[n]=1;
    18     q.push(next);
    19     while(!q.empty())
    20     {
    21         next=q.front();
    22         q.pop();
    23         if(vis[next.x-1]==0&&(next.x-1)>=0&&(next.x-1)<=100000)
    24         {
    25             pos.x=next.x-1; pos.step=next.step+1;
    26             q.push(pos);
    27             vis[next.x-1]=1;
    28             if(pos.x==k)
    29             return pos.step;
    30         }
    31         if(vis[next.x+1]==0&&(next.x+1)>=0&&(next.x+1)<=100000)
    32         {
    33             pos.x=next.x+1; pos.step=next.step+1;
    34             q.push(pos);
    35             vis[next.x+1]=1;
    36             if(pos.x==k)
    37             return pos.step;
    38         }
    39         if(vis[next.x*2]==0&&(next.x*2)>=0&&(next.x*2)<=100000)
    40         {
    41             pos.x=next.x*2; pos.step=next.step+1;
    42             q.push(pos);
    43             vis[next.x+1]=1;
    44             if(pos.x==k)
    45             return pos.step;
    46         }
    47     }
    48     return 0;
    49 };
    50 int main()
    51 {
    52     int n,k,sum;
    53     while(~scanf("%d%d",&n,&k))
    54     {
    55         memset(vis,0,sizeof(vis));
    56         sum=bfs(n,k);
    57         printf("%d
    ",sum);
    58     }
    59 }
  • 相关阅读:
    iOS 面向对象
    iOS 构建动态库
    iOS 单例
    iOS 操作系统架构
    iOS 编译过程原理(1)
    Category
    CoreText
    dyld
    block
    (CoreText框架)NSAttributedString 2
  • 原文地址:https://www.cnblogs.com/bfshm/p/3163166.html
Copyright © 2011-2022 走看看