bfs catch that cow poj3278

这是刚刚写bfs的时候就做过的题了,可是我居然不会写了。意识到这个问题的时候真的好崩溃F**K

本来是想按照逻辑写的,可是没有想到正确的写法,记录走的步骤需要用到结构体,表示走到这一位置至少要经过多少步

每一个走到的位置都需要记录走的步骤数,然后走到终点输出步数

#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<set>
#include<queue>
#include<map>
using namespace std;
int vis[200005],cnt,ed;
struct cow
{
    int pos,step;//位置还有步数
};
cow a[100005];
void bfs(int st)
{
    cow start;
    start.pos=st;
    start.step=0;
    queue<cow>q;//存放结构体的队列
    while(!q.empty())q.pop();
    q.push(start);
    vis[st]=1;
    while(!q.empty())
    {
        cow now=q.front(),temp;//现在的位置
        q.pop();
        //cout<<now.pos<<" "<<now.step<<endl;
        if(now.pos==ed)
        {
            printf("%d\n",now.step);
            break;
        }
        int t=now.pos;//t表示位置
        if(t+1>=0&&t+1<=100000&&!vis[t+1])
        {
            temp.pos=t+1;
            temp.step=now.step+1;//步数等于现在的步数加一
            q.push(temp);
            vis[t+1]=1;//标记为走过了
        }
        if(t-1>=0&&t-1<=100000&&!vis[t-1])
        {
            temp.pos=t-1;
            temp.step=now.step+1;
            q.push(temp);
            vis[t-1]=1;
        }
        if(t*2>=0&&t*2<=100000&&!vis[2*t])
        {
            temp.pos=t*2;
            temp.step=now.step+1;
            q.push(temp);
            vis[2*t]=1;
        }
    }
}
int main()
{
    int st;
    while(scanf("%d%d",&st,&ed)==2)
    {
        memset(vis,0,sizeof(vis));
        bfs(st);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值