POJ3278 Catch That Cow
题目链接:https://vjudge.net/problem/POJ-3278
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。而花花的飞船支持以下两种运动方式:
飞行:在一个时间单位中,能够从坐标x移动到x-1或x+1;
跃迁:在一个时间单位中,能够直接从x跃迁到2x。
现在,花花想知道,他需要多长时间才能到达致远星?
解题思路:利用BFS求出n到k的最短距离,关键在于对搜索过程进行剪枝,省去重复的工作。
Cpp Code
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 1e5 + 5;
int n, k;
bool vis[maxn];//标记数组
int ans[maxn];
queue<int> q;
int bfs(int x,int k){
int cur, next;
ans[x] = 0;
vis[x] = 1;//访问后标记为1,防止重复访问
q.push(x);
while (!q.empty())
{
cur = q.front();
q.pop();
for (int i = 0; i < 3;i++){//三次转换
if(i==0){
next = cur - 1;
}
else if(i==1){
next = cur + 1;
}
else{
next = cur*2;
}
//符合条件才压入队列
if(next>=0&&next<=100000&&vis[next]==0){
vis[next] = 1;
q.push(next);
ans[next] = ans[cur] + 1;
}
if(next==k){
return ans[next];
}
}
/* code */
}
}
int main(){
cin >> n >> k;
fill(vis, vis + maxn, 0);
while (!q.empty())
{
q.pop();
}
if(n>=k){
cout << n - k << endl;
}
else{
cout << bfs(n,k) << endl;
}
return 0;
}
Java Code
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static class node{
int x;//数的值
int num;//次数
node(){}
node(int a,int b){
x=a;
num=b;
}
}
static boolean[] vis=new boolean[(int)1e5+5];//标记数组
static boolean ok(int x) {//判断函数
if(x>=0&&x<=(int)1e5&&vis[x]==false) {
return true;
}
return false;
}
public static int BFS(int n,int k) {
Queue<node> q=new LinkedList<node>();
vis[n]=true;//访问后标记
q.offer(new node(n,0));
node op;
while(!q.isEmpty()) {
op=q.poll();
if(op.x==k) {
return op.num;
}
int x,num=op.num+1;
for(int i=0;i<3;i++) {//三次转换
if(i==0) {
x=op.x-1;
}
else if(i==1) {
x=op.x+1;
}
else {
x=op.x*2;
}
if(ok(x)) {
vis[x]=true;//访问后标记
q.offer(new node(x,num));
}
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n,k;
n=sc.nextInt();
k=sc.nextInt();
System.out.print(BFS(n,k));
// TODO Auto-generated method stub
}
}