问题 B: 最少的步数 【BFS】

问题 B: 最少的步数

时间限制: 1 Sec   内存限制: 128 MB

 

我现在的位置在(0, 0)处,目的地在(0, x)(注:单位是米),我每次可以走1、2、3、4、5米。问最少需要多少步可以到达目的地。

输入

有多组测试数据,每组数据输入一个整数x。(1 <= x <= 1000)。

输出

输出一个结果,代表最少需要走的步数
 

样例输入

2
6

样例输出

1
2
思路
#include<stdio.h>
#include<string.h>
#include<queue>
#include<stack>
#include<algorithm>
#include<math.h>
#include<vector>
#define inf 0x3f3f3f
#define M 10000
using namespace std;
int v[M];
int step[M];
int to[5]={1,2,3,4,5};
void bfs(int st,int ed)
{
    int now,next;
    queue<int >num;
    v[st]=1;step[st]=0;
    num.push(st);
    while(!num.empty())
    {
        now=num.front();
        num.pop();
        if(now==ed) break;
        for(int i=0;i<5;i++)
        {
            next=now+to[i];
            if(!v[next]&&next<=ed)
            {
                step[next]=step[now]+1;
                v[next]=1;
                num.push(next);
            }
        }
    }
    printf("%d\n",step[ed]);
}
int main()
{
    int x;
    while(~scanf("%d",&x))
    {
        memset(v,0,sizeof(v));
        bfs(0,x);
    }
    return 0;
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值