poj1741,POJ3278 HDU2717 Catch That Cow【BFS】

 2023-11-18 阅读 25 评论 0

摘要:Catch That Cow Time Limit: 2000MS?Memory Limit: 65536KTotal Submissions: 100475?Accepted: 31438 Description Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (0 ≤ N ≤ 100,000) on a

Catch That Cow

Time Limit: 2000MS?Memory Limit: 65536K
Total Submissions: 100475?Accepted: 31438

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (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 orX + 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?

poj1741。Input

Line 1: Two space-separated integers: N andK

Output

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

Sample Input

5 17

poj2352、Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

Source

USACO 2007 Open Silver

poj3273,?

問題鏈接:POJ3278 HDU2717 Catch That Cow

題意簡述

? 一條線上,人的FJ的起點為K位置,牛在N位置(牛不動),輸入正整數K和N。若FJ在x位置,FJ有三種走法,分別是走到x-1、x+1或2x位置。求從K走到N的最少步數。

問題分析

? 典型的BFS問題。在BFS搜索過程中,走過的點就不必再走了,因為這次再走下去不可能比上次的步數少。

程序說明

? 程序中,使用了一個隊列來存放中間節點。

? 需要說明的是,除了BFS方法,這個題應該可以用分支限界法來解,需要更高的技巧。

?

AC的C++語言程序如下:

?

/* POJ3278 HDU2717 Catch That Cow */#include <iostream>
#include <cstring>
#include <queue>using namespace std;const int MAXN = 100000;
const int MAXN2 = MAXN * 2;bool notvist[MAXN * 2 + 2];int n, k, ans;struct node {int p, level;
};node start;void bfs()
{queue<node> q;int nextp;memset(notvist, true, sizeof(notvist));notvist[n] = false;start.p = n;start.level = 0;ans = 0;q.push(start);while(!q.empty()) {node front = q.front();q.pop();if(front.p == k) {ans = front.level;break;}nextp = front.p - 1;        /* x-1 */if(nextp >= 0 && notvist[nextp]) {notvist[nextp] = false;node v;v.p = nextp;v.level = front.level + 1;q.push(v);}nextp = front.p + 1;        /* x+1 */if(nextp <= MAXN2 && notvist[nextp]) {notvist[nextp] = false;node v;v.p = nextp;v.level = front.level + 1;q.push(v);}nextp = front.p + front.p;      /* 2x */if(nextp <= MAXN2 && notvist[nextp]) {notvist[nextp] = false;node v;v.p = nextp;v.level = front.level + 1;q.push(v);}}
}int main()
{while(cin >> n >> k) {bfs();printf("%d\n", ans);}return 0;
}

?

?

?

?

?

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/176009.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息