• hdu 2717:Catch That Cow(BFS)


    http://acm.hdu.edu.cn/showproblem.php?pid=2717

    Problem Description

    Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

    * Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
    * Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

    If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

    Input

    Line 1: Two space-separated integers: N and K

    Output

    Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

    Sample Input

    5 17

    Sample Output

    4

    题意分析:

    一个人要找他的牛,当前位置为x,每次可以去的地方有x+1, x-1, x*2,求到达牛的位置需要多少步。

    解题思路:

    每次对当前位置BFS,下一步可能是x+1, x-1, x*2,已经走过的不用再走,注意数组越界。

    #include <stdio.h>
    #include <string.h>
    #include <queue>
    #define N 200020
    using namespace std;
    bool book[N]; 
    struct date{
    	int x;
    	int temp;
    };
    int bfs(int s, int t)
    {
    	int tx;
    	memset(book, false, sizeof(book));
    	queue<date>q;
    	book[s]=true;
    	
    	q.push(date{s, 0});
    	while(!q.empty())
    	{
    		date u=q.front();
    		q.pop();
    		if(u.x==t)
    			return u.temp;
    		tx=u.x+1;
    		if(book[tx]==false && tx>=0 && tx<=t+2)
    		{
    			book[tx]=true;
    			q.push({tx, u.temp+1});
    		}
    		tx=u.x-1;
    		if(book[tx]==false && tx>=0 && tx<=t+2)
    		{
    			book[tx]=true;
    			q.push({tx, u.temp+1});
    		}
    		tx=u.x*2;
    		if(book[tx]==false && tx>=0 && tx<=t+2)
    		{
    			book[tx]=true;
    			q.push({tx, u.temp+1});
    		}
    	}
    }
    int main()
    {
    	int n, k;
    	while(scanf("%d%d", &n, &k)!=EOF)
    	{
    		if(n>k)
    			printf("%d
    ", n-k);
    		else
    			printf("%d
    ", bfs(n, k));	
    	}
    	return 0;
    } 
  • 相关阅读:
    Linux A机器免密码SSH登录B机器
    Linux 系统命令笔记
    整理笔记有感而发
    Linux(Centos)快速搭建SVN
    APP接口自动化测试JAVA+TestNG(三)之HTTP接口测试实例
    Windows服务器环境下jenkins下载和安装
    Win10系统如何在防火墙里开放端口
    Java 通过地址获取经纬度
    一、springBoot简介与环境搭建
    2018年尚硅谷《全套Java、Android、HTML5前端视频》
  • 原文地址:https://www.cnblogs.com/zyq1758043090/p/11852551.html
Copyright © 2020-2023  润新知