HDU1548

采用优先队列求解最少次数,也就是题目给你Ki,代表楼层数,你可以选择按下按钮,向上或者向下,最后选择最少的次数到达要去的楼层。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int maxx=205;
int vis[maxx];
int ans[maxx];
int n;
int A,B;
struct node{
	int times;
	int s;
	bool friend operator<(const node a,const node b){
		return a.times>b.times;
	}
};
int bfs(int s){
	priority_queue<node>q;
    node a;
    a.times=0;
    a.s=s;
    q.push(a);
    vis[s]=1;
    while(!q.empty()){
    	node u=q.top();
    	q.pop();
    	if(u.s==B){
    		return u.times;
		}
		for(int i=-1;i<=1;i+=2){
			node t;
			t.s=u.s+i*ans[u.s];
			if(vis[t.s]==0&&t.s>0&&t.s<=n){
				vis[t.s]=1;
				t.times=u.times+1;
				q.push(t);
			}
		}
	}
	return -1;
}
int main(){
	while(cin>>n){
		if(n==0)break;
		cin>>A>>B;
		for(int i=1;i<=n;i++){
			scanf("%d",&ans[i]);
		}
		vis[A]=1;
		memset(vis,0,sizeof(vis));
		int flag=bfs(A);
		if(flag!=-1){
			cout<<flag<<endl;
		}else{
			cout<<-1<<endl;
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值