6 条题解

  • 0
    @ 2025-3-17 22:04:08

    BFS

    #include <iostream>
    #include <cstring>
    #include <queue>
    
    using namespace std;
    
    const int N = 210;
    int n, a, b;
    int arr[N], d[N];
    int m[2] = {1, -1};
    queue<int> q;
    
    int bfs(int a, int b) // a, b 为下标(电梯楼层)
    {
    	q.push(a);
    	
    	d[a] = 0;
    	
    	while (!q.empty())
    	{
    		int t = q.front();
    		q.pop();
    		
    		for (int i = 0; i <= 1; i++)
    		{
    			int nx = t + arr[t] * m[i];
    			
    			if (nx >= 1 && nx <= n && d[nx] == -1)
    			{
    				d[nx] = d[t] + 1;
    				q.push(nx);
    			}
    		}
    	}
    	return d[b];
    }
    
    int main()
    {
    	cin >> n >> a >> b;
    	
    	for (int i = 1; i <= n; i++) cin >> arr[i];
    	
    	memset(d, -1, sizeof d);
    	
    	cout << bfs(a, b);
    	
    	return 0;
    }
    

    信息

    ID
    85
    时间
    1000ms
    内存
    256MiB
    难度
    7
    标签
    递交数
    776
    已通过
    174
    上传者