AT_abc359_e 题解

· · 题解

思路

设 x 表示最后一个满足 h_x\ge h_i 且 x<i 的模板,显然要使 i 号点灌到水那么就要把 x 以后的地方全都淹没到 h_i 为止,所以 ans_i=ans_x+(i-x)\times h_i。

怎么求 x 呢?显然,若 h_j<h_i,则 x_i\ge x_j。所以,我们只要从 i-1 开始,一路往上跳,直到 h_j\ge h_i 为止。然后把 x_i,ans_i 存下来输出就行。

代码

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int n, h[200005], lst[200005];
ll ans[200005];
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> n;
    h[0] = 1e9 + 5, ans[0] = 1;
    for (int i = 1; i <= n; ++ i) {
        cin >> h[i];
        lst[i] = i - 1;
        while (h[i] > h[lst[i]])
            lst[i] = lst[lst[i]];
        cout << (ans[i] = ans[lst[i]] + (ll) (i - lst[i]) * h[i]) << ' ';
    }
    return 0;
}