zoukankan      html  css  js  c++  java
  • POJ 3278 Catch That Cow [BFS]

    1.题意:给定两个数N,K,N表示初始状态,K表示目标状态,有三种操作:+1,-1和*2,试求这个过程的最少的操作次数;

    2.输入输出:依次给出N,K;

    3.分析:典型的BFS求最小操作数,唯一注意的就是搜索过程中注意状态值不要超出K的范围:[0,1e5];

     1 # include <iostream>
     2 # include <cstdio>
     3 # include <queue>
     4 using namespace std;
     5 const int maxn=1e5+10;
     6 int N,K;
     7 int vis[maxn];
     8 struct Node
     9 {
    10     int X,T;
    11     Node(){}
    12     Node(int x,int t)
    13     {
    14         X=x;
    15         T=t;
    16     }
    17 };
    18 void Init()
    19 {
    20     for(int i=0;i<maxn;i++)
    21         vis[i]=0;
    22     vis[N]=1;
    23 }
    24 void Solve()
    25 {
    26     int ans=-1;
    27     queue<Node> q;
    28     q.push(Node(N,0));
    29     while(!q.empty())
    30     {
    31         Node temp=q.front();
    32         q.pop();
    33         if(temp.X==K) 
    34         {
    35             ans=temp.T;
    36             break;
    37         }
    38         if(temp.X+1<maxn&&!vis[temp.X+1])
    39         {
    40             vis[temp.X+1]=1;
    41             q.push(Node(temp.X+1,temp.T+1));
    42         }
    43         if(temp.X-1>=0&&!vis[temp.X-1])
    44         {
    45             vis[temp.X-1]=1;
    46             q.push(Node(temp.X-1,temp.T+1));
    47         }
    48         if(temp.X*2<maxn&&!vis[temp.X*2])
    49         {
    50             vis[temp.X*2]=1;
    51             q.push(Node(temp.X*2,temp.T+1));
    52         }
    53     }
    54     printf("%d
    ",ans);
    55 }
    56 int main()
    57 {
    58     while(scanf("%d%d",&N,&K)!=EOF)
    59     {
    60         Init();
    61         Solve();
    62     }
    63     return 0;
    64 }
  • 相关阅读:
    foreach_and_函数
    集合
    二维数组
    二维数组的操作
    字符串类型的一些操作
    数组循环的操作及思路
    数组操作
    js各种获取当前窗口页面宽度、高度的方法
    Jquery 获取 radio选中值,select选中值
    jQuery效果:隐藏、显示、切换、滑动、淡入淡出、动画
  • 原文地址:https://www.cnblogs.com/cnXuYang/p/6649041.html
Copyright © 2011-2022 走看看