zoukankan      html  css  js  c++  java
  • hdu_2717_Catch That Cow_bfs

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

    题解:一维简单BFS,详细看代码,0ms。

     1 #include<cstdio>
     2 #include<queue>
     3 using namespace std;
     4 const int maxn=100002;
     5 bool v[maxn];
     6 int n,k;
     7 struct nd{
     8     int x,step;
     9 };
    10 bool check(int x){
    11     if(x<0||x>100000||v[x])return false;
    12     else return true;
    13 }
    14 int bfs(int s){
    15     for(int i=0;i<=100000;i++)v[i]=false;//初始化标记
    16     queue<nd>Q;
    17     nd S;
    18     S.x=s,S.step=0;
    19     v[s]=1;
    20     Q.push(S);
    21     while(!Q.empty()){
    22         nd now=Q.front();Q.pop();
    23         if(now.x==k)return now.step;
    24         if(check(now.x+1)){
    25             nd tmp;tmp.x=now.x+1,tmp.step=now.step+1;
    26             v[tmp.x]=1;
    27             Q.push(tmp);
    28         }
    29         if(check(now.x-1)){
    30             nd tmp;tmp.x=now.x-1,tmp.step=now.step+1;
    31             v[tmp.x]=1;
    32             Q.push(tmp);
    33         }
    34         if(check(now.x*2)){
    35             nd tmp;tmp.x=now.x*2,tmp.step=now.step+1;
    36             v[tmp.x]=1;
    37             Q.push(tmp);
    38         }
    39     }
    40     return -1;
    41 }
    42 int main(){
    43     while(~scanf("%d%d",&n,&k)){
    44         if(n>=k){printf("%d
    ",n-k);continue;}//剪枝
    45         int ans=bfs(n);
    46         printf("%d
    ",ans);
    47     }
    48     return 0;
    49 }
    View Code
  • 相关阅读:
    排序算法:冒泡排序
    排序算法: 插入排序
    排序算法:折半插入排序
    排序算法:快速排序
    浅谈C/C++回调函数(Callback)& 函数指针
    仿函数
    回溯法:求和
    动态规划:数字和为sum的方法数
    字典序
    剑指offer15 二进制中1的个数
  • 原文地址:https://www.cnblogs.com/bin-gege/p/5696188.html
Copyright © 2011-2022 走看看