• C


      这是我第一次遇到的BFS问题,因为要学习编程,F同学帮我找了一些搜索的题目,做到这个问题的时候感觉无法使用DFS来写,因为他可能是个无底洞。因为当时没有学习过BFS,所以网上搜索了下发现了也是一位第一次碰到BFS题目就是C - Catch That Cow的博主,学习了他的代码,他的代码解释很清楚。

      感谢博主,传送门http://blog.csdn.net/weiwanshu/article/details/45770537

      题目的意思是农民的牛丢了,农民不知道牛在哪里,只能一点一点的去寻找,已知的是农民和牛在一条直线上,农民需要找到他的牛。农民有两种行走方法,一种是走,一分钟可以前进1个单位也可以后退1个单位,第二种方法是跳跃,每次只能向前跳,跳的位置是当前位置的2倍。给出农民和牛的位置求出最快多久找到牛。

    样例

    Sample Input
    5 17
    Sample Output
    4
    

    代码

    #include<stdio.h>
    #include<string.h>
    struct A {
        int state;
        int step;
    }queue[100001];
    int n,k;
    int bfs(int start);
    int book[100001];
    int main(){
        scanf("%d%d",&n,&k);
        memset(book,0,sizeof(book));
        if(n>=k) printf("%d",n-k);
        else printf("%d",bfs(n));
    }
    int bfs(int start){
        struct A temp;
        int head=0;
        int rear=0;
        queue[head].state=start;
        queue[rear++].step=0;
        book[start]=1; 
        while(head<rear){
            temp=queue[head++];
            if(temp.state+1>0&&temp.state+1<100001&&book[temp.state+1]==0){
                queue[rear].state=temp.state+1;
                queue[rear++].step=temp.step+1;
                book[temp.state+1]=1;
                if(temp.state+1==k)
                    return temp.step+1;         
            } 
            if(temp.state-1>0&&temp.state-1<100001&&book[temp.state-1]==0){
                queue[rear].state=temp.state-1;
                queue[rear++].step=temp.step+1;
                book[temp.state-1]=1;
                if(temp.state-1==k)
                    return temp.step+1;         
            } 
            if(temp.state*2>0&&temp.state*2<100001&&book[temp.state*2]==0){
                queue[rear].state=temp.state*2;
                queue[rear++].step=temp.step+1;
                book[temp.state*2]=1;
                if(temp.state*2==k)
                    return temp.step+1;         
            } 
        }
        return 0;
    }
  • 相关阅读:
    Java NIO使用及原理分析(二)(转)
    Java NIO使用及原理分析 (一)(转)
    虚拟机字节码执行引擎
    虚拟机类加载机制
    浅析Java中的final关键字
    java内存模型7-处理器内存模型
    java内存模型6-final
    最小生成树
    有向图的基本算法
    并查集(Union-Find)算法介绍
  • 原文地址:https://www.cnblogs.com/lvcoding/p/6557453.html
Copyright © 2020-2023  润新知