top1编程
← 返回题目
题解

【基础】奇怪的电梯

1 条题解

  • 0
    @ 2026-7-29 0:17:37
    #include <bits/stdc++.h>
    using namespace std;
    
    long long n, a, b;
    long long c[210];
    bool f [330];
    
    struct s{
    	long long floor;
    	long long step;
    };
    
    void bfs (){
    	queue <s> p;
    	s temp;
    	temp.floor = a;
    	temp.step = 0;
    	p.push (temp);
    	while (!p.empty()){
    		s now = p.front ();
    		long long floor = now.floor, step = now.step;
    		long long sh = floor + c[floor], xi = floor - c[floor];
    		p.pop ();
    		if (floor == b){
    			cout << step;
    			return ;
    		}
    		if (sh >= 1 && sh <= n && !f[sh]){
    			f[sh] = true;
    			s temp;
    			temp.floor = sh;
    			temp.step = step + 1;
    			p.push (temp);
    		}
    		if (xi >= 1 && xi <= n && !f[xi]){
    			f[xi] = true;
    			s temp;
    			temp.floor = xi;
    			temp.step = step + 1;
    			p.push (temp);
    		}
    	}
    	cout << -1;
    	return ;
    }
    
    int main(){
    	cin >> n >> a >> b;
    	for (int i=1;i<=n;i++){
    		cin >> c[i];
    	}
    	if (a == b){
    		cout << 0;
    		return 0;
    	}
    	bfs ();
    	return 0;
    }
    
    • 1