Source Code
#include "bits/stdc++.h"

using namespace std;
typedef long long ll;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n;
    cin >> n;
    vector<ll> a, ok;   
    ll profit = 0;
    for(int i = 0; i < n; i++) {
        int x;
        cin >> x;
        if(x < 0) profit += x;
        else a.push_back(x); 
    }
    n = a.size();
    ok.resize(n);

    priority_queue<pair<int, int>, vector<pair<int,int>>, greater<>> pq;
    for(int i = 0; i < n - 1; i++) {
        pq.push({a[i], i});
    }

    int idx = 0;
    while(pq.size()) {
        pair<int, int> u = pq.top();
        pq.pop();
        if(!ok[u.second]) {
            for(; idx < u.second; idx++) {
                if(!ok[idx]) {
                    a[n - 1] += a[idx];
                    ok[idx] = 1;
                }
            }
            idx = u.second + 1;
        }
    }

    vector<ll> ans;
    for(int i = 0; i < n; i++) {
        if(!ok[i])
            ans.push_back(a[i]);
    }

    while(ans.size()) {
        if(ans.back() == 0) ans.pop_back();
        else break;
    }

    if(ans.size() == 0) ans.push_back(profit);
    else ans[0] += profit;

    for(auto x : ans) {
        cout << x << ' ';
    }
}
Copy
a OsamaX01
GNU G++17
0 ms
732 KB
Wrong Answer