poj 3278 Catch That Cow (BFS剪枝)

题意是让你从N位置去抓K位置的牛牛~注意N,K大小不能确定~,你可以有三种走法,n+1或n-1或n*2。


第一次想到求最短路,用bfs,用的不够灵活,代码很幼稚,活生生的TLE。

TLE代码:

#include<stdio.h>
#include<queue>
using namespace std;

struct point
{
    int x;
    int step;
};

int bfs(int s,int e)
{
    queue<point> Q;
    point now,next;

    now.x=s;
    now.step=0;
    Q.push(now);

    while(!Q.empty())
    {
        now=Q.front();
        Q.pop();

        for(int i=0; i<3; i++)
        {
            if(i==0)
                next.x=now.x+1;
            else if(i==1)
            {
                if(now.x==1)
                    continue;
                next.x=now.x-1;
            }

            else if(i==2)
            {
                if(now.x==0)
                    continue;
                next.x=now.x*2;
            }

            if(next.x==-1||next.x==100001)
                continue;
            else if(next.x==e)
            {
                //printf("         %d\n",next.x);
                return now.step+1;
            }

            else
            {
                next.step=now.step+1;
                //vis[next.x]=1;
                Q.push(next);
                // printf("    %d\n",next.x);
            }
        }
    }
}

int main()
{
    int star,end;
    while(scanf("%d%d",&star,&end)!=EOF)
    {
        printf("%d\n",bfs(star,end));
    }
    return 0;
}

第二次参考了别人的家的孩子,加了剪枝,飙泪过关。

时间和空间用的比较多。4744K,313MS

代码:

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

int step[1000001];

int bfs(int s,int e)
{
    queue<int> Q;
    int now;
    now=s;
    step[now]=1;
    Q.push(now);
    while(!Q.empty())
    {
        now=Q.front();
        Q.pop();

        if(now==e)
            return step[now]-1;
        if(now>=2&&step[now-1]==0)   //-1
        {
            step[now-1]=step[now]+1;
            Q.push(now-1);
        }
        if(now<=999999&&step[now+1]==0)   //+1
        {
            step[now+1]=step[now]+1;
            Q.push(now+1);
        }
        if(now<=500000&&step[2*now]==0)   //*2
        {
            step[2*now]=step[now]+1;
            Q.push(2*now);
        }
    }
}

int main()
{
    int star,end;
    while(scanf("%d%d",&star,&end)!=EOF)
    {
        if(star>end)
            printf("%d",star-end);
        else
        {
            memset(step,0,sizeof(step));
            printf("%d\n",bfs(star,end));
        }
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值