您的位置:首页 > 其它

poj 3278:Catch That Cow(简单一维广搜)

2014-07-22 11:37 405 查看
Catch That Cow

Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 45648Accepted: 14310
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.
Source

USACO 2007 Open Silver

  简单一维广搜
  题意
  你在一个一维坐标的n位置,牛在k位置,你要从n到k,抓到那头牛。你可以有三种走法,n+1,n-1,或者n*2直接跳。求你抓到那头牛的最短步数。
  思路
  简单广搜的思想。状态跳转的时候有三种跳转的方式,将新的状态放到队列中,再不断提取队列中最前面的状态,直到找到k位置。
  代码

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;

bool isw[100010];

struct Node{
int x;
int s;
};

bool judge(int x)
{
if(x<0 || x>100000)
return true;
if(isw[x])
return true;
return false;
}

int bfs(int sta,int end)
{
queue <Node> q;
Node cur,next;
cur.x = sta;
cur.s = 0;
isw[cur.x] = true;
q.push(cur);
while(!q.empty()){
cur = q.front();
q.pop();
if(cur.x==end)
return cur.s;
//前后一个个走
int nx;
nx = cur.x+1;
if(!judge(nx)){
next.x = nx;
next.s = cur.s + 1;
isw[next.x] = true;
q.push(next);
}
nx = cur.x-1;
if(!judge(nx)){
next.x = nx;
next.s = cur.s + 1;
isw[next.x] = true;
q.push(next);
}
//向前跳
nx = cur.x*2;
if(!judge(nx)){
next.x = nx;
next.s = cur.s + 1;
isw[next.x] = true;
q.push(next);
}
}
return 0;
}

int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF){
memset(isw,0,sizeof(isw));
int step = bfs(n,k);
printf("%d\n",step);
}
return 0;
}


Freecode : www.cnblogs.com/yym2013
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: