信息學奧賽:1360:奇怪的電梯(lift)
題目鏈接
思路:
還是bfs,但bfs用到了隊列。
建一個一維數組s,下標表示樓層,值表示當前樓層上的那個數。
一開始沒有對走過的層數做標記,會一直死循環導致內存超限。
後來,做了標記,但做的不對,用的是走過的樓層i,把s[i]置爲-1;
改正了標記的錯誤,在最後還是用新建一個一位數組bol來標記。
#include<iostream>
#include<queue>
using namespace std;
const int N = 205;
int s[N];
bool bol[N] = {false}; // VS在這裏會全部初始化false,我也這樣默認的,結果oj通過了
int n, A, B;
struct Point {
int x, step;
};
int bfs(int start) {
bol[start] = true; // 走過的樓層標記
queue<Point>q;
Point now, next;
now.x = start;
now.step = 0;
q.push(now);
while (!q.empty()) {
now = q.front();
if (now.x == B)
return now.step;
// 判斷能否上
next.x = now.x + s[now.x]; // 這之前我沒有把s[now.x]置爲-1,因爲這裏要用到
if (0 < next.x && next.x <= n && !bol[next.x]) {
bol[next.x] = true;
next.step = now.step + 1;
q.push(next);
}
// 判斷是否能下
next.x = now.x - s[now.x];
if (0 < next.x && next.x <= n && !bol[next.x]) {
bol[next.x] = true;
next.step = now.step + 1;
q.push(next);
}
q.pop();
}
return -1;
}
int main() {
cin >> n >> A >> B;
for (int i = 1; i <= n; i++)
cin >> s[i];
cout << bfs(A);
//getchar();
//getchar();
return 0;
}
和同學討論的時候很簡單,動手的時候盡然花了幾個小時。