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

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double dd;
#define all(v) v.begin(),v.end()
#define endl "\n"
#define clr(n, r) memset(n,r,sizeof(n))
typedef bitset<10> MASK;

void fast() {
    cin.tie(0);
    cin.sync_with_stdio(0);
}
//
//bool comp(pair<ll, ll> &a, pair<ll, ll> &b) {
//    if (a.first == b.first)return a.second > b.second;
//    return a.first < b.first;
//}
const ll oo = LLONG_MAX;
int main() {
    fast();
    ll n;
    cin >> n;
    vector<ll> arr;
    bool neg = 0;
    ll summNeg = 0;
    for (ll i = 0; i < n; ++i) {
        ll a;
        cin >> a;
        if (a >= 0)arr.push_back(a);
        else {
            if (!neg) {
                arr.push_back(a);
                neg = 1;
            }
            summNeg += a;
        }
    }
    n = arr.size();
    deque<pair<ll, ll>> v;
    for (ll i = 0; i < n; ++i) {
        if (arr[i] < 0) {
            arr[i] = summNeg;
        }
        if (i < n - 1)v.push_back({arr[i], i});
    }
    sort(all(v));
    if (arr.back() < 0&&arr.size()>1) {
        int val=arr.back();
        arr.pop_back();
        n--;
        for (int i = 0; i <v.size() ; ++i) {
            if(v[i].second==0||v[i].second<n-1){
                v[i].first+=val;
                arr[v[i].second]+=val;
                break;
            }
        }
    }
    n = arr.size();
    ll sum = 0,ok =0;
    if(!v.empty()) {
        for (ll i = 0; i < n - 1; ++i) {
            if (!ok &&v.front().second==n-1)v.pop_front(),ok=1;
            if (arr[i] == v.front().first) {
                v.pop_front();
                continue;
            }
            sum += arr[i];
            arr[i] = oo;
        }
        arr[n-1]+=sum;
    }
    for (ll i = n-1; i >=1 ; --i) {
        if(arr[i]==0)arr[i]=oo;
        else break;
    }
    for (ll i = 0; i <n ; ++i) {
        if(arr[i] !=oo)cout<<arr[i]<<" ";
    }

}
Copy
a 7eem
GNU G++17
0 ms
500 KB
Wrong Answer