a402中等雙向鄰居鏈・事件佇列

APCS 2020/01:砍樹 (ZeroJudge h028)

刪除能倒下的樹,只重新檢查受影響的相鄰站立樹。

前往題目練習 →回報教學錯誤時間 O(N),空間 O(N);以迭代佇列處理連鎖砍除。

這題在學什麼

一棵樹能向左倒,等價於 c[i]−h[i]≥左鄰樹位置;能向右倒則等價於 c[i]+h[i]≤右鄰樹位置。最外側用 0、L 當邊界哨兵。題面明確允許碰到端點,所以兩式使用大於等於與小於等於。只要一側成立就能砍。

用 left[i]、right[i] 維持仍站立樹的雙向鏈,先把全部樹加入待檢查佇列。若 i 可砍,記錄數量與最高高度,把它的左右鄰居直接相連,並把這兩個鄰居重新放入佇列;已被砍過的編號直接跳過。

刪除 i 只會改變它兩個鄰居的最近障礙,其他樹的可砍性不變,故只重查鄰居便足夠。障礙被移除不會讓原本可砍者變成不可砍;搭配題目保證的順序無關性,佇列清空時得到最終可砍集合。每次刪除至多新增兩次檢查,因此總檢查數為 O(N)。

Step-by-step animation

公開範例一:以可行順序示範連鎖移除

回報動畫錯誤
步驟 1 / 4

先砍位置 30

高度 15 向左覆蓋 [15,30],左鄰樹在 10,沒有被壓到。

10:h30
30:h15 ×
50:h55
70:h10
100:h55
125:h25
已砍
1
最大高度
15

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    long long limit;
    cin >> n >> limit;
    vector<long long> c(n + 2), height(n + 2);
    for (int i = 1; i <= n; ++i) cin >> c[i];
    for (int i = 1; i <= n; ++i) cin >> height[i];
    c[n + 1] = limit;
    vector<int> left(n + 2), right(n + 2);
    vector<bool> alive(n + 2, true);
    queue<int> pending;
    for (int i = 1; i <= n; ++i) {
        left[i] = i - 1;
        right[i] = i + 1;
        pending.push(i);
    }
    int count = 0;
    long long highest = 0;
    while (!pending.empty()) {
        int i = pending.front();
        pending.pop();
        if (!alive[i]) continue;
        int a = left[i], b = right[i];
        if (c[i] - height[i] < c[a] && c[i] + height[i] > c[b]) continue;
        alive[i] = false;
        ++count;
        highest = max(highest, height[i]);
        right[a] = b;
        left[b] = a;
        if (a >= 1) pending.push(a);
        if (b <= n) pending.push(b);
    }
    cout << count << '\n' << highest << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多