Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 58434 | Accepted: 18161 |
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.
思路:
对于任意起点,只有三种操作,即*2,+1,-1;每次操作所得值若小于100000且未访问过即入队列,当该值等于终点即求出最少步数。
代码:
#include<iostream>
#include<queue>
using namespace std;
int dis[100001],vis[100001];//dis[]步数,vis[]是否访问
int main()
{
int n,k;
int l;
cin>>n>>k;
queue<int> q;
q.push(n);
dis[n]=0;
while(!q.empty())
{
l=q.front();
q.pop();
vis[l]=1;
if(l==k)
break;
if( l-1>=0 && vis[l-1]==0)
{
q.push(l-1);
vis[l-1] = 1;
dis[l-1] = dis[l]+1;
}
if( l+1<=100000 && vis[l+1]==0)
{
q.push(l+1);
vis[l+1] = 1;
dis[l+1] = dis[l]+1;
}
if( l*2<=100000 && vis[l*2]==0)
{
q.push(l*2);
vis[l*2]=1;
dis[l*2]=dis[l]+1;
}
}
cout<<dis[l]<<endl;
return 0;
}
memory 980K time 16Ms
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <cstdio>
#include <climits>
using namespace std;
bool data[100005] = {0};
int que[100005] = {0};
int tnum[100005] = {0};
void bfs(int n, int k)
{
int front = 0, rear = 0;
que[0] = n;
data[n] = true;
tnum[0] = 0;
rear++;
while (front != rear)
{
int t = que[front];
int tn = tnum[front];
if (t == k)
{
printf("%d\n", tn);
return;
}
if (t > 0 && !data[t-1])
{
data[t-1] = true;
que[rear] = t-1;
tnum[rear] = tn+1;
rear++;
}
if (t < 100000 && !data[t+1])
{
data[t+1] = true;
que[rear] = t+1;
tnum[rear] = tn+1;
rear++;
}
if (t <= 50000 && !data[t*2])
{
data[t*2] = true;
que[rear] = t*2;
tnum[rear] = tn+1;
rear++;
}
front++;
}
printf("0\n");
}
int main()
{
int n, k;
scanf("%d%d", &n, &k);
memset(data, 0, sizeof(data));
bfs(n, k);
return 0;
}