洛谷:奇怪的电梯

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼上有一个数字Ki,电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。​从1楼开始。在1楼,按“上”可以到4楼,按“下”是不起作用的,因为没有−2楼。那么,从A楼到B楼至少要按几次按钮呢?

dfs

#include<bits/stdc++.h>
using namespace std;
int n,a[100001],end,ans=999999999,book[100001];
void dfs(int x,int t)
{
	if(x==end)
	{
		ans=min(ans,t);
		return;
	}
	if(t>ans)
		return ;
	if(x-a[x]>0&&!book[x-a[x]]) book[x-a[x]]=1,dfs(x-a[x],t+1),book[x-a[x]]=0;
	if(x+a[x]<=n&&!book[x+a[x]]) book[x+a[x]]=1,dfs(x+a[x],t+1),book[x+a[x]]=0;
}
int main()
{
	int i,sta;
	cin>>n>>sta>>end;
	for(i=1;i<=n;i++)
		cin>>a[i];
	book[sta]=1;
	dfs(sta,0);
	if(ans==999999999)
		cout<<"-1"<<endl;
	else
		cout<<ans<<endl;
	return 0;
}

bfs

#include<bits/stdc++.h>
using namespace std;
typedef struct point
{
	int x,t;
}P;
queue<P> q;	
P now,temp;
int main()
{
	int n,sta,end,i,j,a[100001],book[100001]={0};
	cin>>n>>sta>>end;
	for(i=1;i<=n;i++)
		cin>>a[i];
	P start={sta,0};
	book[sta]=1;
	q.push(start);
	while(!q.empty())
	{
		now=q.front();
		if(now.x==end)
			break;
		if(now.x+a[now.x]<=n&&book[now.x+a[now.x]]==0)
		{
			book[now.x+a[now.x]]=1;
			temp={now.x+a[now.x],now.t+1};
			q.push(temp);
		}
		if(now.x-a[now.x]>0&&book[now.x-a[now.x]]==0)
		{
			book[now.x-a[now.x]]=1;
			temp={now.x-a[now.x],now.t+1};
			q.push(temp);
		}
		q.pop();
	}
	if(now.x==end)
		cout<<now.t<<endl;
	else
		cout<<"-1"<<endl;
	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值