hdoj 1548 A strange lift(bfs)

【题目大意】:给出n层楼,每层楼可以乘坐电梯,规定在第i层乘坐的电梯移动的层数为ki,可以向上移动也可以向下移动,每移动一次要按一次电梯,且移动完不能低于1层,也不能高于n层。问从a到b最少按多少次电梯。


【解题思路】:bfs


【代码】:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
                   
using namespace std;
                   
#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long

int cnt[250];
int tmp,n,s,t;
int mapp[250][5];
int vis[250];

void solve_cnt(){
    queue<int> que;
    que.push(s);
    for (int i=1; i<=n; i++) cnt[i]=inf;
    memset(vis,0,sizeof(vis));
    cnt[s]=0;
    vis[s]=1;
    while (!que.empty()){
        int q;
        q=que.front();
        que.pop();
        if (mapp[q][0]!=0 && vis[mapp[q][0]]==0) {
            if (cnt[mapp[q][0]]>=cnt[q]+1) {
                cnt[mapp[q][0]]=cnt[q]+1;
                que.push(mapp[q][0]);
                vis[mapp[q][0]]=1;
            }
        }
        if (mapp[q][1]!=0 && vis[mapp[q][1]]==0) {
            if (cnt[mapp[q][1]]>=cnt[q]+1) {
                cnt[mapp[q][1]]=cnt[q]+1;
                que.push(mapp[q][1]);
                vis[mapp[q][1]]=1;
            }
        }
    }
    if (cnt[t]!=inf) printf("%d\n",cnt[t]);
    else printf("-1\n");
}

int main() {
    while (~scanf("%d",&n)){
        if (n==0) break;
        scanf("%d%d",&s,&t);
        memset(mapp,0,sizeof(mapp));
        for (int i=1; i<=n; i++){
            scanf("%d",&tmp);
            if (i-tmp>=1) {mapp[i][0]=i-tmp;}
            if (i+tmp<=n) {mapp[i][1]=i+tmp;}
        }
        solve_cnt();
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值