POJ - 3278抓到那头牛!

4 篇文章 0 订阅

C - Catch That Cow POJ - 3278
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.
    脑海里的模型:一维的搜索
    解法:跟二维的不同也是在于方向,是规定的三个,要么+1,要么-1,要么*2,BFS找出最短路径
    遇到的阻碍就是第一次提交时Runtime erro,我开的数组是100005,没有考虑到要判断农夫 teleporting的时候会让标记数组超出边界,于是我加了个判断他不能走到小于0或者超过100000
    第二次提交wa的原因是,当农夫和牛一开始就在同一个地方的时候没有判断
    以下是BFS代码:
#include<iostream>
#include<queue>
using namespace std;
int N,K;
bool vis[300005];
struct node{
    int x;
    int step;
};
void bfs(){
    queue<node>q;
    node n;
    n.step=0;
    n.x=N;
    q.push(n);
    while(!q.empty()){
        node tmp=q.front();
        q.pop();
        n.step=tmp.step+1;
        vis[N]=1;
        int t[3];
        t[0]=tmp.x+1;
        t[1]=tmp.x-1;
        t[2]=tmp.x*2;
        for(int i=0;i<3;i++){
            if(vis[t[i]]!=1&&t[i]>=0&&t[i]<=100000){
            if(t[i]==K){
                cout<<n.step<<endl;
                return ;
            }
            vis[t[i]]=1;
            n.x=t[i];
            q.push(n);
            }
        }
    }
}
int main(){

    cin>>N>>K;
    if(N==K)
        cout<<'0'<<endl;
    else
    bfs();
    return 0;
}

To conclusion:广搜的题做多之后发现套路都差不多,要是想要统计层数的话,开全局变量我是行不通的,所以得要用一个结构体来存每一个点它被搜到时候的层数,然后下一层的时候再用队列pop出来的那个上一层的点的层数加一就好了
还有一点就是别忘了用标记数组。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值