poj3278 Catch That Cow

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 73973   Accepted: 23308

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

QAQ,写循环队列wa了好久。。。默默改大队列范围。

可行性剪枝:第一,当前点在牛的左边才进行右移;第二,当前点不能为负数。

15793310

  ksq2013 3278 Accepted 1816K 32MS G++ 1159B 2016-07-23 19:37:16
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int n,cow;
bool vis[200100];
struct que{
int fmr,stp;
}q[201000];
int bfs()
{
int head=0,tail=1;
q[0].fmr=n;
q[0].stp=0;
vis[n]=1;
while(head^tail){
que now=q[head++];
//if(head==10000)head=0;
if(!(now.fmr^cow))return now.stp;
if(now.fmr-1>=0&&!vis[now.fmr-1]){
vis[now.fmr-1]=1;
q[tail].fmr=now.fmr-1;
q[tail].stp=now.stp+1;
tail++;
//if(tail==10000)tail=0;
}
if(now.fmr<=cow&&!vis[now.fmr+1]){
vis[now.fmr+1]=1;
q[tail].fmr=now.fmr+1;
q[tail].stp=now.stp+1;
tail++;
//if(tail==10000)tail=0;
}
if(now.fmr<=cow&&!vis[now.fmr<<1]){
vis[now.fmr<<1]=1;
q[tail].fmr=now.fmr<<1;
q[tail].stp=now.stp+1;
tail++;
//if(tail==10000)tail=0;
}
}
}
int main()
{
while(~scanf("%d%d",&n,&cow)){
memset(q,0,sizeof(que));
memset(vis,0,sizeof(vis));
printf("%d\n",bfs());
}
return 0;
}
上一篇:SpringBoot实战 之 接口日志篇


下一篇:软件公司为何要放弃MongoDB?