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, ll>mp;
    vector<ll>sor;
    ll s_n = 0;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    bool p = 0;
    ll w = 0;
    while (a.size()&&a.back() < 0)
    {
        w += a.back();
        a.pop_back();
    }
   // cout << w << endl;
    if (sz(a) != n)
    {
        bool pp = 0;
        for (int i = 0; i < sz(a); i++)
        {
            if (a[i] <= 0)
            {
                pp = 1;
                a[i] += w;
                break;
            }
        }
        if (!pp||sz(a) == 0)a.push_back(w);
    }
    n = sz(a);
    for (int i = n-2; i >=0 ; i--)
    {       
        if (a[i] < 0 )s_n += a[i];
    }
    p = 1;
    ll ss = 0;
    for (int i = 0; i < n; i++)
    {
        if (a[i] < 0)
        {
            if (!p)continue;
            if (i == n - 1)
            {
                sor.push_back(a[i]);
                b.push_back(a[i]);
                mp[a[i]]++;
                break;
            }
            sor.push_back(s_n);
            b.push_back(s_n);
            mp[s_n]++;
            p = 0;
        }
        else
        {
            if (!mp[a[i]])
                sor.push_back(a[i]);
            b.push_back(a[i]);
            mp[a[i]]++;
        }
    }
    sort(all(sor));
    reverse(all(sor));
    /*for (auto it : b)cout << it << ' ';
    cout << endl;
    for (auto it : sor)cout << it << ' ';
    cout << endl;*/
    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]]--;
        }
    }
    if (b.back() < 0)
    {
        if(c.size())
        c.front() += b.back();
        else
        {
            c.push_back(b.back());
        }
        c.back() += s;

    }
    else
    {
        c.push_back(b.back() + s);
    }
    sort(all(c));
    for (int i = 0; i < sz(c); i++)
    {
        cout << c[i]; if (i < sz(c) - 1)cout << ' ';
    }
}
Copy
a Ramy
GNU G++17
0 ms
576 KB
Wrong Answer