zoukankan      html  css  js  c++  java
  • POJ 3278 经典BFS

    进一步了解了bfs;

    题意:给你n,然后用+,-,*三种运算使n变成k;

    漏洞:在算出新的数字之后,一定要判边界,否则RE,而且在每一步后面都得加判断是否等于K,如果是即刻退出,否则WA,判这个的时候需要顺序;

    不过不明白为什么bfs这两个顺序为啥结果不同

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <queue>
     5 #define N 101000
     6 using namespace std;
     7 int d[301000],vis[301000];
     8 int k,n;
     9 int OK(int t)
    10 {
    11     if(t < 0 || t > N)
    12         return 0;
    13     return 1;
    14 }
    15 int bfs()
    16 {
    17     queue<int> q;
    18     q.push(n);
    19     memset(d,0,sizeof(d));
    20     memset(vis,0,sizeof(vis));
    21     d[n] = 0;
    22     vis[n] = 1;
    23     int s;
    24     while(!q.empty())
    25     {
    26         int t = q.front();
    27         q.pop();
    28 //        if(s == k)///满足条件才能到这一条
    29 //            return d[s];
    30         for(int i=0; i<3; i++)
    31         {
    32             if(i==0) s = t + 1;
    33             if(i==1) s = t - 1;
    34             if(i==2) s = t * 2;
    35             if(OK(s)&&!vis[s])
    36             {
    37                 vis[s] = 1;
    38                 q.push(s);
    39                 d[s] = d[t] + 1;
    40             }
    41             else
    42                 continue;
    43             if(s == k)///满足条件才能到这一条,放在上边就错了,为啥啊
    44                 return d[s];
    45         }
    46     }
    47     return -1;
    48 }
    49 int main()
    50 {
    51     while(~scanf("%d%d",&n,&k))
    52     {
    53         if(n>=k)
    54             cout<<n-k<<endl;
    55         else
    56             cout<<bfs()<<endl;
    57     }
    58     return 0;
    59 }
    View Code
  • 相关阅读:
    一、操作m'y's'ql
    十三、并发
    十二、异步_实践
    一、数据
    【2019-08-13】琐碎事才是突破
    【2019-08-12】迟到好过没到
    【2019-08-11】别人约我宵夜,我却约人早茶
    【2019-08-10】习惯跟时间有关
    【2019-08-09】一日之计在于晨
    【2019-08-08】少即是多,慢即是快
  • 原文地址:https://www.cnblogs.com/ACMERY/p/4438474.html
Copyright © 2011-2022 走看看