b754中等

整數高度的正峰平臺

以端點掃描找整數格上的正峰,保留零變化事件的合併語義。

解題思路

閉區間 [l,r] 加 w 轉成 l 的 +w 與 r+1 的 -w。先加總同座標事件,再移除總變化為 0 的座標,因為那裡沒有高度改變,不應分裂平臺。相鄰事件座標 x[i],x[i+1] 之間代表整數區間 [x[i],x[i+1]-1],其長度為差值。

掃描得到所有有限非零變化分段後,兩端以高度 0 補上外界。某段高 h>0 且 h 同時大於左右鄰段時恰是正峰;累計個數與段長,以高度最大、左端點最小選代表。事件已移除零變化,因此每段都是極大的,不會把相接且等高的資料算成兩峰。

時間 O(n log n),空間 O(n);Python 輸入 token、事件字典與分段皆 O(n)。n≤1200,座標可達 ±10^9,長度與高度加總使用 64 位。

Step-by-step animation

逐步推演(例子條件見步驟說明)

回報動畫錯誤
步驟 1 / 3

建立事件

自訂 [0,1]+2、[2,3]+2,事件 2 的變化抵消。

0
2
4
座標2淨變化
0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int n;
    cin >> n;
    map<ll, ll> ev;
    while (n--) {
        ll l, r, w;
        cin >> l >> r >> w;
        ev[l] += w;
        ev[r + 1] -= w;
    }
    vector<pair<ll, ll>> e;
    for (auto p : ev)
        if (p.second)
            e.push_back(p);
    vector<ll> h, len, left;
    ll cur = 0;
    for (int i = 0; i + 1 < (int)e.size(); i++) {
        cur += e[i].second;
        h.push_back(cur);
        left.push_back(e[i].first);
        len.push_back(e[i + 1].first - e[i].first);
    }
    ll cnt = 0, sum = 0, high = 0, start = 0;
    for (int i = 0; i < (int)h.size(); i++)
        if (h[i] > 0 && h[i] > (i ? h[i - 1] : 0) &&
            h[i] > (i + 1 < (int)h.size() ? h[i + 1] : 0)) {
            cnt++;
            sum += len[i];
            if (h[i] > high) {
                high = h[i];
                start = left[i];
            }
        }
    cout << cnt << ' ' << sum << ' ' << high << ' ' << start << '\n';
}

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

更多