Catch That Cow
Posted whitabbit
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Catch That Cow相关的知识,希望对你有一定的参考价值。
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
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.
给你两个数N和K,你可以对N进行三种操作,N=N-1,N=N+1,N=N*2,要求在操作数最小的情况下,使N==K,直接BFS暴力搜就行,可以分为以下三种情况进行剪枝(当然,暴力将100000个点搜完也能AC)
令N=N-1时,保证next>=0
令N=N+1时,保证next<=k
令N=N*2时,保证next<=k或者next-e+1<e-no
当next<=k,一定能减少到达终点时的操作数(当然,N==1时不影响总操作数);
当next>e,我们这时剩余部分的步数已经确定了(因为只能通过N=N-1使N==K),这时就要比较一下进行该操作和不进行该操作的情况下,e-now就时不进行操作的剩余步数,next-e就是进行操作时的剩余操作数,由于N=N*2也花费了一次操作所以应该加1,而两者相同的情况下自然也不必进行这个操作,毕竟操作数都是一样的
注意:总共只有100000个点,所以也要保证next<=100000
#include <algorithm> #include <bitset> //#include <bits/extc++.h> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <queue> using namespace std; //using namespace __gnu_pbds #define ll long long #define maxn 105 int s, e, step[100005]; bool vis[100005]; void bfs() { queue<int> q; q.push(s); vis[s] = 0; step[s] = 0; while (!q.empty()) { int now = q.front(); q.pop(); int next = now + 1; if (next <= e && vis[next]) { vis[next] = false; step[next] = step[now] + 1; q.push(next); } if (next == e) { return; } next = now - 1; if (next >= 0 && vis[next]) { vis[next] = false; step[next] = step[now] + 1; q.push(next); } if (next == e) { return; } next = now << 1; if ((next <= e || next - e + 1 < e - now) && next <= 100000 && vis[next]) { vis[next] = false; step[next] = step[now] + 1; q.push(next); } if (next == e) { return; } } } int main() { while (~scanf("%d%d", &s, &e)) { memset(vis, true, sizeof(vis)); if (s >= e) { printf("%d ", s - e); //剪枝 } else { bfs(); printf("%d ", step[e]); } } return 0; }
以上是关于Catch That Cow的主要内容,如果未能解决你的问题,请参考以下文章