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

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 45648   Accepted: 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 - 1 or + 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

 
  简单一维广搜
  题意
  你在一个一维坐标的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[]; struct Node{
int x;
int s;
}; bool judge(int x)
{
if(x< || x>)
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 = ;
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+;
if(!judge(nx)){
next.x = nx;
next.s = cur.s + ;
isw[next.x] = true;
q.push(next);
}
nx = cur.x-;
if(!judge(nx)){
next.x = nx;
next.s = cur.s + ;
isw[next.x] = true;
q.push(next);
}
//向前跳
nx = cur.x*;
if(!judge(nx)){
next.x = nx;
next.s = cur.s + ;
isw[next.x] = true;
q.push(next);
}
}
return ;
} int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF){
memset(isw,,sizeof(isw));
int step = bfs(n,k);
printf("%d\n",step);
}
return ;
}

Freecode : www.cnblogs.com/yym2013

上一篇:Entity Framework Code Migration 新建、更新数据库


下一篇:新浪微博客户端开发之OAuth认证篇