Source Code
#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define sz(s)    (int)(s.size())
#define endl "\n"
#define BI acos(-1)
#define all(a) a.begin(), a.end()

void Open() {
#ifndef ONLINE_JUDGE
#endif  !ONLINEJUDGE
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
}
int dx[]{ 1, -1, 0, 0, 1, 1, -1, -1 };
int dy[]{ 0, 0, 1, -1, 1, -1, 1, -1 };
const int OO = 0x3f3f3f3f;

int main()
{
    Open();
    int n;
    cin >> n;
    vector<ll>a(n), b,c;
    map<ll, int>mp;
    vector<ll>sor;
    ll s_n = 0;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    bool p = 0;
    for (int i = n-1; i >=0 ; i--)
    {
        if (a[i] > 0)p = 1;
        if (a[i] <= 0 && p)s_n += a[i];
    }
    p = 1;
    ll ss = 0;
    for (int i = 0; i < n; i++)
    {
        if (a[i] <= 0)
        {
            ss += a[i];
            
            if (ss <= s_n)
            {
                if (!mp[a[i]])
                    sor.push_back(a[i]);
                b.push_back(a[i]);
                mp[a[i]]++;
            }// 5 4 3 2 1
        }
        else
        {
            if (!mp[a[i]])
                sor.push_back(a[i]);
            b.push_back(a[i]);
            mp[a[i]]++;
        }
    }
    /*for (auto it : b)cout << it << ' ';
    cout << endl;*/
    sort(all(sor));
    reverse(all(sor));
    ll s = 0;
    if (sor[0] <= 0)
    {
        
        for (int i = 0; i < n; i++)s += a[i];
        cout <<  s;
        return 0;
    }
    //cout << endl;
    for (int i = 0; i < sz(b)-1; i++)
    {
        while (!sor.empty()&&mp[sor.back()] == 0)
        {
            sor.pop_back();
        }
        if (sor.back() == b.back() && mp[sor.back()] == 1)sor.pop_back();
        if (b[i] != sor.back())
        {
            s += b[i];
            mp[a[i]]--;
        }
        else
        {
            c.push_back(b[i]);
            mp[b[i]]--;
        }
    }
    for (auto it : c)cout << it << ' ';
    cout << b.back() + s;
}
Copy
a Ramy
GNU G++17
0 ms
508 KB
Wrong Answer