现在的位置: 首页 > 综合 > 正文

POJ 3278 Catch That Cow (BFS)

2018年01月12日 ⁄ 综合 ⁄ 共 1721字 ⁄ 字号 评论关闭
Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 35117   Accepted: 10823

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.


解题思路:
输入两个数,先判断两者是否相同。若相同,则直接输出 0 ,若不相同,则进行广度优先搜索。
要注意的地方时,每次搜索的时候,要标记已经找过的数。因为没有标记,悲剧的超内存了。。。

代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
int n,k,map[100005]={0};
struct node
{
    int t;
    int x;
};
queue<node> q;
int find(node start)
{
    int i;
    q.push(start);
    map[start.x]=1;
    while(!q.empty())
    {
        node temp;
        temp=q.front();
        q.pop();
        for (i=1; i<=3; i++)
        {
            node next;
            if (i==1)
            {
                next.x=temp.x-1;
                if (next.x>=0 && next.x<100001 && !map[next.x])
                {
                    next.t=temp.t+1;
                    q.push(next);
                    map[next.x]=1;
                }
            }
            if (i==2)
            {
                next.x=temp.x+1;
                if (next.x>=0 && next.x<100001 && !map[next.x])
                {
                    next.t=temp.t+1;
                    q.push(next);
                    map[next.x]=1;
                }
            }
            if (i==3)
            {
                next.x=temp.x*2;
                if (next.x>=0 && next.x<100001 && !map[next.x])
                {
                    next.t=temp.t+1;
                    q.push(next);
                    map[next.x]=1;
                }
            }
            if (next.x==k)
                return next.t;
        }
    }

}
int main ()
{
    node start;
    start.t=0;
    int s=0;
    cin>>start.x>>k;
    if (start.x==k)
        cout<<s<<endl;
    else
    {
        s=find(start);
        cout<<s<<endl;
    }
    return 0;
}

抱歉!评论已关闭.