Catch That Cow

来源:互联网 发布:网络预约挂号平台 编辑:程序博客网 时间:2024/05/22 12:38

1186: Catch That Cow

时间限制: 2 Sec  内存限制: 64 MB

题目描述

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?

输入

multiple cases, each case has two space-separated integers: N and K in one line.

输出

for each case, output the least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow in one line.

样例输入

5 173 7

样例输出

42

提示

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.


没用STL的队列去实现的,但是它这里的数组大小不好控制,不知道要多大才行啊!

WA代码:


#include<iostream>#include<cstring>using namespace std;int n,m;int f[200010],cow[7000100],cnt[7000100];void bfs(){    int head=0,tail=0,t;    cow[tail++]=n;    while (head<tail)    {        if(cow[head]==m){cout << cnt[head] << endl;break;}        if(!f[head])        {            t=cow[head]-1;            if (t<=m+1&&t>=0)            {                cnt[tail]=cnt[head]+1;                cow[tail++]=t;            }            t=cow[head]+1;            if (t<=m+1&&t>=0)            {                cnt[tail]=cnt[head]+1;                cow[tail++]=t;            }            t=cow[head]*2;            if (t<=m+1&&t>=0)            {                cnt[tail]=cnt[head]+1;                cow[tail++]=t;            }        }        f[head]=1;        head++;    }}int main(){    while (cin >> n >> m)    {        memset(f,0,sizeof(f));        memset(cnt,0,sizeof(cnt));        bfs();    }    return 0;}

AC代码:


#include<iostream>#include<cstring>#include<queue>using namespace std;int n,m;int f[100010];struct S{int cow;int cnt;};queue<S> Cow;S p,q;int bfs(){int t;p.cnt=0;p.cow=n;Cow.push(p);while (!Cow.empty()){p=Cow.front();Cow.pop();if(f[p.cow])continue;f[p.cow]=1;if(p.cow==m)return p.cnt;t=p.cow+1;if (t<=m+1){q.cnt=p.cnt+1;q.cow=t;Cow.push(q);}t=p.cow-1;if (t<=m+1){q.cnt=p.cnt+1;q.cow=t;Cow.push(q);}t=p.cow*2;if (t<=m+1){q.cnt=p.cnt+1;q.cow=t;Cow.push(q);}}}int main(){while (cin >> n >> m){if(m<n){cout << n-m << endl;continue;}memset(f,0,sizeof(f));cout << bfs() << endl;while (!Cow.empty()){Cow.pop();}}return 0;}


0 0
原创粉丝点击