洛谷 P1135 奇怪的电梯(BFS实现)

洛谷 P1135 奇怪的电梯


又是一道 广搜

最开始交了一次只过了四个点,还有两个点MLE,其余的T了。很纳闷,数据规模只有200,BFS居然会T。后来思考了一下,发现有好多重复的点,比如:有多个楼层都可以到达某一楼层,那么到达的这个楼层就可以不用再入队了 所以我用了一个check[ ]数组用来判断第i层有没有去过,0表示没有去过,1表示去过。之后正常搜就好了。

上代码:

#include <queue>
#include <stdio.h>
using namespace std;
struct node{
    
    
	int floor;//楼层 
	int time;//按键次数 
};
int k[210],n,a,b,check[210];

int bfs(int begin)
{
    
    
	int sum=0,next_f;
	node now,next;
	queue<node>q;
	now.floor=begin;
	now.time=sum;
	q.push(now);
	while(!q.empty()){
    
    
		now=q.front();
		if(now.floor==b) return now.time;//如果已经到了终点就结束 
		q.pop();
		for(int i=0;i<2;i++){
    
    
			next_f=now.floor;
			sum=now.time;
			if(i==0) next_f+=k[now.floor];
			else next_f-=k[now.floor];
			if(next_f>=1&&next_f<=n&&check[next_f]==0){
    
    //判断   check数组在这里判断是否到达过 
				sum+=1;
				next.floor=next_f;
				next.time=sum;
				q.push(next);
				check[next_f]=1;
			}
		}
	}
	return -1;
}
int main()
{
    
    
	int r;
	scanf("%d %d %d",&n,&a,&b);
	for(int i=1;i<=n;i++){
    
    
		scanf("%d",&k[i]);
		check[i]=0;//赋初始值为0,任何楼层都没去过 
	} 
	r=bfs(a);
	printf("%d\n",r);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45743427/article/details/108906402