• poj 3278 Catch That Cow


    题意:一个人站在N点,一头牛站在K点,这个人要到达牛的位置,他每分钟只能到达N+1,N-1,和2*N的位置,求最少要多少分钟。

    思路:好久不做搜索题竟然将它忘的干干净净了,唉。这题让求最少时间,当然用BFS,开始做的时候竟然没想起来,然后做的时候,竟然将队列写成了栈,浪费了好长时间,看来还要坚强训练啊。

    代码:

    View Code
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <iostream>
    #include <algorithm>
    #include <queue>
    #define  N  100005
    using namespace std ;
    
    struct node
    {
        int num ;
        int step ;
    };
    
    int f[N] ;
    
    int main()
    {
        int n , k ;
    
        while ( scanf ( "%d%d" , &n , &k ) != EOF )
        {
            //n和k相等
            if ( n == k )
            {
                printf ( "0\n" );
                continue ;
            }
            //若n>k,则他只能通过每次N-1的方式到达。
            else if ( n > k )
            {
                printf ( "%d\n" , n - k );
                continue ;
            }
            //否则,BFS搜索。
            else
            {
                queue<node>q ;
                node p , t , x ;
                memset( f , 0 , sizeof ( f )) ;
                p.num = n ;
                p.step = 0 ;
                q.push( p );
                f[n] = 1 ;
                int minx = N ;
                while ( !q.empty())
                {
                    t = q.front();
                    q.pop();
                    if ( t.num == k )
                    {
                        if ( minx > t.step )
                        minx = t.step ;
                        continue ;
                    }
                    if ( t.num - 1 > n/2 && !f[t.num - 1])
                    {
                        f[t.num-1] = 1 ;
                        x.num = t.num - 1 ;
                        x.step = t.step + 1 ;
                        q.push( x );
                    }
                    if ( t.num + 1 <= k + 1 && !f[t.num + 1])
                    {
                        f[t.num+1] = 1 ;
                        x.num = t.num + 1 ;
                        x.step = t.step + 1 ;
                        q.push( x );
                    }
                    if ( 2 * t.num <= k + 1 && !f[2*t.num])
                    {
                        f[2*t.num] = 1 ;
                        x.num = 2 * t.num ;
                        x.step = t.step + 1 ;
                        q.push( x );
                    }
                }
                printf ( "%d\n" , minx );
            }
        }
        return 0 ;
    }
  • 相关阅读:
    C#执行sql文件
    "C:Program FilesInternet Exploreriexplore.exe" -extoff 无加载项启动IE 浏览器打开时全屏模式
    sql server备份与还原 sql语句
    触摸屏\串口服务器\串口
    USB串行端口
    选取所有表单元素
    C# Bitmap类型与Byte[]类型相互转化
    本文介绍C# BitmapData
    C#多线程学习(六) 互斥对象
    C# List 复制克隆副本
  • 原文地址:https://www.cnblogs.com/misty1/p/2717317.html
Copyright © 2020-2023  润新知