POJ 3278 Catch That Cow

来源:互联网 发布:vb中len函数的使用方法 编辑:程序博客网 时间:2024/06/08 03:24
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 54362 Accepted: 16996
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


第一道广度优先搜索,以前只用了memset没用STL,以后用memset的时候,头文件就是#include <cstring>,

接下来就按照广度优先搜索的思路做这道题。



#include <iostream>#include <cstdio>#include <cstring>#include <queue>#include <algorithm>#include <stdlib.h>using namespace std;int maxn;int N,K;int vis[100005];int b[100005],a[100005];int main(void){    //int N,K;    scanf("%d%d",&N,&K);    memset(vis,0,sizeof(vis));    memset(a,0,sizeof(a));    memset(b,0,sizeof(b));    queue <int> p;    p.push(N);    a[N]=0;    while(!p.empty())    {        int tmp=p.front();        if(tmp==K) break;        b[tmp]=1;        p.pop();        if(tmp+1<=100000&&b[tmp+1]==0)        {            a[tmp+1]=a[tmp]+1;            p.push(tmp+1);            b[tmp+1]=1;        }        if(tmp-1>=0&&b[tmp-1]==0)        {            a[tmp-1]=a[tmp]+1;            p.push(tmp-1);            b[tmp-1]=1;        }        if(tmp*2<=100000&&b[tmp*2]==0)        {            a[tmp*2]=a[tmp]+1;            p.push(tmp*2);            b[tmp*2]=1;        }    }//       p.clear(); printf("%d\n",a[K]);    return 0;}


0 0
原创粉丝点击