其他分享
首页 > 其他分享> > C2 - Skyscrapers (hard version)

C2 - Skyscrapers (hard version)

作者:互联网

前几天做的题,当时好像是超时了,这个博客写的超好https://blog.csdn.net/lucky52529/article/details/89155694

用单调站解决问题。

代码是从另外一篇博客来的,谢谢了,贴过来,如果介意的话我就删掉

https://blog.csdn.net/weixin_44164153/article/details/104486676?fps=1&locationNum=2

#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;
}

 

标签:Skyscrapers,int,res,hard,pos,back,maxn,push,C2
来源: https://www.cnblogs.com/SunChuangYu/p/12369741.html