CodeForces - 1313C2 Skyscrapers (hard version) 单调栈

CodeForces - 1313C2 Skyscrapers (hard version)

原题地址:

http://codeforces.com/contest/1313/problem/C2

题意:

给出每个位置能设定的大小的上限,要你给每个位置设定实际大小满足 j < i < k 并且 aj > ai < ak ( j 和 k 不要求和 i 相邻)
也就是说找到一个中心点,满足这个点左边非递减,右边非递增的来构造每一个点的实际大小,使它们的和最大。

基本思路:

单调栈先从左边维护在每个位置 i 时维持区间 [ 1 - i ] 非递减所能得到的最大值记录在 l [i] 中;同理从右边维护区间 [ N - i ] 非递减能得到的最大值记录在 r [i] 中 。
那么位置 i 作为中心点时所能得到的实际和就为 r[i] + l [i] - a[i] ,取最大值所在的位置为中心,按照条件往两边构造答案就可以了。

参考代码:

#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define INF 0x3f3f3f3f

const int maxn = 5e5+10;
int n,a[maxn],l[maxn],r[maxn],res[maxn];
signed main() {
    IO;
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];
    vector<int> q;
    q.push_back(0);
    for (int i = 1; i <= n; i++) {
        while (!q.empty() && a[q.back()] >= a[i]) q.pop_back();
        int t = q.back();
        l[i] = l[t] + a[i] * (i - t);
        q.push_back(i);
    }
    q.clear();
    q.push_back(n+1);
    for (int i = n; i >= 1; i--) {
        while (!q.empty() && a[q.back()] >= a[i]) q.pop_back();
        int t = q.back();
        r[i] = r[t] + a[i] * (t - i);
        q.push_back(i);
    }
    int ans = 0, pos = 0;
    for (int i = 1; i <= n; i++) {
        int temp = l[i] + r[i] - a[i];
        if (temp > ans) {
            ans = temp, pos = i;
        }
    }
    res[pos] = a[pos];
    for (int i = pos - 1; i >= 1; i--) res[i] = min(a[i], res[i + 1]);
    for (int i = pos + 1; i <= n; i++) res[i] = min(a[i], res[i - 1]);
    for (int i = 1; i <= n; i++) cout << res[i] << " ";
    cout << endl;
    return 0;
}


发布了23 篇原创文章 · 获赞 7 · 访问量 1748

猜你喜欢

转载自blog.csdn.net/weixin_44164153/article/details/104486676
今日推荐