0
点赞
收藏
分享

微信扫一扫

POJ 3278 Catch That Cow/信息奥赛一本通 1253:抓住那头牛

眸晓 2023-02-07 阅读 76


Catch That Cow

Time Limit: 2000MS

Memory Limit: 65536K

Total Submissions: 113166

Accepted: 35425

Description

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

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

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

Input

Line 1: Twospace-separated integers: N and K

Output

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

Sample Input

5 17

Sample Output

4

Hint

The fastest wayfor 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​​

算法分析:

题意:

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:

1、从X移动到X-1或X+1,每次移动花费一分钟

2、从X移动到2*X,每次移动花费一分钟

分析:bfs思想。

 

#include<cstdio>  
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
using namespace std;
const double eps = 1e-8;
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 1e5 + 10;
const int MAXT = 10000 + 10;
#define N 1000000
int n,m,vis[N];
int bfs()
{
memset(vis,0,sizeof(vis));
queue<int>q;


q.push(n);
int t=0;
while(!q.empty())
{
int t=q.front();
q.pop();
if(t==m)
{
printf("%d",vis[t]);
break;
}
//三种路径
if(t>0&&!vis[t-1])
{
q.push(t-1);
vis[t-1]=vis[t]+1;
}
if(t<m&&!vis[t+1])
{
q.push(t+1);
vis[t+1]=vis[t]+1;
}
if(2*t<N&&!vis[2*t])//注意此时的t*2的范围
{
q.push(2*t);
vis[2*t]=vis[t]+1;
}
}
return 0;
}
int main()
{

while(scanf("%d%d",&n,&m)!=EOF)
{
if(n>m) //巧妙剪枝,在农夫前面直接往前找最快
{
printf("%d\n",n-m);
continue;
}
bfs();

}
return 0;

}


举报

相关推荐

0 条评论