列表

详情


NC25080. [USACO 2007 Ope S]Catch That Cow

描述

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?

输入描述

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

输出描述

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

示例1

输入:

5 17

输出:

4

说明:

Farmer John starts at point 5 and the fugitive cow is at point 17.
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.

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(g++ 7.5.0) 解法, 执行用时: 4ms, 内存消耗: 896K, 提交时间: 2023-04-24 17:26:25

#include<bits/stdc++.h>
int n,k,a[100001];
std::queue<int>q;
int main(){
	std::cin>>n>>k;
	q.push(n);
    a[n]=1;
	while(!a[k]){
		int u=q.front();
		q.pop();
		if(u<=99999&&!a[u+1])a[u+1]=a[u]+1,q.push(u+1);
		if(u>=1&&!a[u-1])a[u-1]=a[u]+1,q.push(u-1);
		if(u<=50000&&!a[u*2])a[u*2]=a[u]+1,q.push(u*2);
	}
	std::cout<<a[k]-1;
}

上一题