• POJ3278Catch That Cow


    转载请注明出处:優YoU http://user.qzone.qq.com/289065406/blog/1303558739

     

    大致题意:

    给定两个整数nk

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

    输出最少的操作次数

     

    解题思路:

    说实话,要不是人家把这题归类到BFS,我怎么也想不到用广搜的= = 自卑ing。。。

     

    水题水题,三入口的BFS

     

    注意的地方有二:

    1、  由于用于广搜的 队列数组 标记数组  相当大,如果定义这两个数组时把它们扔到局部去,编译是可以的,但肯定执行不了,提交就等RE= =

    大数组必须开为 全局 。。。常识常识。。。

    2、  剪枝。直接广搜一样等着RE= =

    不剪枝的同学试试输入n=0  k=100000。。。。。。铁定RE

    怎么剪枝看我程序

     1 //Memory Time 
    2 //1292K 0MS
    3
    4 #include<iostream>
    5 using namespace std;
    6
    7 const int large=200030;
    8
    9 typedef class
    10 {
    11 public:
    12 int x;
    13 int step;
    14 }pos;
    15
    16 int n,k;
    17 bool vist[large]; //数组较大,必须开为全局数组,不然肯定RE
    18 pos queue[large];
    19
    20 void BFS(void)
    21 {
    22 int head,tail;
    23 queue[head=tail=0].x=n;
    24 queue[tail++].step=0;
    25
    26 vist[n]=true;
    27
    28 while(head<tail)
    29 {
    30 pos w=queue[head++];
    31
    32 if(w.x==k)
    33 {
    34 cout<<w.step<<endl;
    35 break;
    36 }
    37
    38 if(w.x-1>=0 && !vist[w.x-1]) //w.x-1>=0 是剪枝
    39 {
    40 vist[w.x-1]=true;
    41 queue[tail].x=w.x-1;
    42 queue[tail++].step=w.step+1;
    43 }
    44 if(w.x<=k && !vist[w.x+1]) //w.x<=k 是剪枝
    45 {
    46 vist[w.x+1]=true;
    47 queue[tail].x=w.x+1;
    48 queue[tail++].step=w.step+1;
    49 }
    50 if(w.x<=k && !vist[2*w.x]) //w.x<=k 是剪枝
    51 {
    52 vist[2*w.x]=true;
    53 queue[tail].x=2*w.x;
    54 queue[tail++].step=w.step+1;
    55 }
    56 }
    57
    58 return;
    59 }
    60
    61 int main(void)
    62 {
    63 while(cin>>n>>k)
    64 {
    65 memset(vist,false,sizeof(vist));
    66 BFS();
    67 }
    68
    69 return 0;
    70 }
  • 相关阅读:
    2.SpringBoot整合Mybatis(一对一)
    1.SpringBoot整合Mybatis(CRUD的实现)
    JavaScript addEventListener()事件监听方法
    jQuery 选择器有61种你都知道了多少
    JavaScript AJAX PHP
    JavaScript BOM Cookie 的用法
    JavaScript Location 对象用法
    JavaScript Date 日期属性和方法
    css3伪类和伪元素你都懂了吗
    css position 5种不同的值的用法
  • 原文地址:https://www.cnblogs.com/lyy289065406/p/2122511.html
Copyright © 2020-2023  润新知