zoukankan      html  css  js  c++  java
  • hdu2717(广度优先搜索)

    acer 生涯的第一道Bfs,终于ac了。刚开始与深搜弄混了,自己也晕了一上午。()

    还有就是queue中几个函数的用法;

    pop()//删除队首元素

    front()获得队首元素

    push()//

    back(),empty()//

     1 #include <iostream>
    2 #include <queue>//注意与<queue.h>的区别
    3 using namespace std;
    4 const int Max=100001;
    5 queue <int>q;
    6 int used[Max];
    7 int step[Max];
    8 int totle;
    9 void Bfs(int k,int s,int e)
    10 {
    11
    12
    13 while(!q.empty())
    14 {
    15 int n;
    16 int head;
    17 head=q.front();
    18 //cout<<"head:"<<head<<endl;
    19 q.pop();
    20 if(head==k)
    21 break;
    22 n=head;
    23 //used[n]=1;
    24 if(n-1>=0&&!used[n-1])
    25 {
    26 q.push(n-1);
    27 used[n-1]=1;
    28 step[n-1]=step[n]+1;
    29 }
    30 if(n+1<=e&&!used[n+1])
    31 {
    32 q.push(n+1),used[n+1]=1;
    33 step[n+1]=step[n]+1;
    34 }
    35 if(n*2<=e&&!used[n*2])
    36 {
    37 q.push(n*2),used[n*2]=1;
    38 step[n*2]=step[n]+1;
    39 }
    40
    41 }
    42
    43 }
    44 int main()
    45 {
    46 int k,n;
    47 while(cin>>n>>k)
    48 {
    49 if(n>=k)
    50 cout<<n-k<<endl;
    51 else
    52 {
    53 while(!q.empty())
    54 q.pop();
    55
    56 memset(step,0,sizeof(step));
    57 memset(used,0,sizeof(used));
    58 used[n]=1;
    59 step[n]=0;
    60 totle=n+(k-n)*2;
    61 if(totle>100000)
    62 totle=100000;
    63 /*if(n-1>=0&&!used[n-1])
    64 {q.push(n-1);used[n-1]=1;step[n-1]=step[n]+1;}
    65 if(n+1<=totle&&!used[n+1])
    66 {q.push(n+1);used[n+1]=1;step[n+1]=step[n]+1;}
    67 if(n*2<=totle&&!used[n*2])
    68 {q.push(n*2),used[n*2]=1;step[n*2]=step[n]+1;}
    69 int head=q.front();
    70 q.pop();
    71 */
    72 q.push(n);
    73 Bfs(k,0,totle);
    74 cout<<step[k]<<endl;
    75 //head=q.front();
    76 //cout<<head<<endl;
    77
    78 }
    79 }
    80 return 0;
    81
    82 }
  • 相关阅读:
    没事千万不要升级VirtualBox和Vagrant!
    以太坊开源项目
    以太坊合约第三方库
    Redis dbfilename
    SUSE Redis 开机启动
    SUSE Linux Enterprise Server 12 SP3 安装redis 6.0以上版本
    HTML基础练习
    html基础
    关于css 浮动的例子
    css 实现三角形
  • 原文地址:https://www.cnblogs.com/orangeblog/p/2413668.html
Copyright © 2011-2022 走看看