洛谷 P1135 奇怪的电梯 【基础BFS】
#include <bits/stdc++.h> using namespace std; #define REP(i,s,t) for(int i=s;i<=t;i++) const int N = 205; struct Node { int x, step; }; queue<Node>q; int arr[N], vis[N]; int n, a, b; int bfs() { Node now, next; while(!q.empty()) { now = q.front(); q.pop(); if(now.x == b) { return now.step; } if(now.x + arr[now.x] <= 200 && !vis[now.x + arr[now.x]]) { //向上坐电梯 next.x = now.x + arr[now.x], next.step = now.step + 1; vis[next.x] = 1; q.push(next); } if(now.x - arr[now.x] >= 1 && !vis[now.x - arr[now.x]]) { //向下坐电梯 next.x = now.x - arr[now.x], next.step = now.step + 1; vis[next.x] = 1; q.push(next); } } return -1; } int main() { cin >> n >> a >> b; memset(vis, 0, sizeof(vis)); REP(i,1,n) scanf("%d", &arr[i]); Node now; now.x = a, now.step = 0; q.push(now); cout << bfs() <<endl; return 0; }
2018-05-31
作者:is_ok
出处:http://www.cnblogs.com/00isok/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。