poj 3278 Catch That Cow(bfs)

题意:给定两个整数nk,通过 n+1n-1 n*2 3种操作,使得n==k,输出最少的操作次数。

bfs题,dfs会超时。

方法一:

#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>

#define MAX 100005
using namespace std;

queue<int> q;
int step[MAX]; //跟随数组,记录步数
bool visit[MAX];
int n,k;
int next,head;

int bfs()
{
    q.push(n);
    step[n]=0;
    visit[n]=1;
    while(!q.empty())
    {
        head=q.front();
        q.pop();
        //分三个方向BFS
        for(int i=0; i<3 ; i++)
        {
            if(i==0) next=head-1;
            else if(i==1) next=head+1;
            else  next=head*2;
            if(next>MAX || next<0 )  continue;  //必须先判断,不然会RE,数组越界了
            if(!visit[next])
            {
                q.push(next);
                step[next]=step[head]+1;
                visit[next]=1;
            }
            if(next==k)  return step[next];
        }
    }
    return -1;
}

int main()
{
    memset(visit,0,sizeof(visit));
    scanf("%ld%ld",&n,&k);
    if(n>=k)
    {
        printf("%d",n-k);
    }
    else
    {
        printf("%d",bfs());
    }
    return 0;
}

方法二:

//Memory Time
//1292K   0MS

#include<iostream>
using namespace std;

const int large=200030;

typedef class
{
public:
    int x;
    int step;
} pos;

int n,k;
bool vist[large];   //数组较大,必须开为全局数组,不然肯定RE
pos queue[large];

void BFS(void)
{
    int head,tail;
    queue[head=tail=0].x=n;
    queue[tail++].step=0;

    vist[n]=true;

    while(head<tail)
    {
        pos w=queue[head++];

        if(w.x==k)
        {
            cout<<w.step<<endl;
            break;
        }

        if(w.x-1>=0 && !vist[w.x-1])     //w.x-1>=0  是剪枝
        {
            vist[w.x-1]=true;
            queue[tail].x=w.x-1;
            queue[tail++].step=w.step+1;
        }
        if(w.x<=k && !vist[w.x+1])     //w.x<=k  是剪枝
        {
            vist[w.x+1]=true;
            queue[tail].x=w.x+1;
            queue[tail++].step=w.step+1;
        }
        if(w.x<=k && !vist[2*w.x])     //w.x<=k  是剪枝
        {
            vist[2*w.x]=true;
            queue[tail].x=2*w.x;
            queue[tail++].step=w.step+1;
        }
    }

    return;
}

int main(void)
{
    while(cin>>n>>k)
    {
        memset(vist,false,sizeof(vist));
        BFS();
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值