Source Code
#include<bits/stdc++.h>

using namespace std;
typedef long long ll;

#define FAST ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define mp make_pair
#define pb push_back
#define lp(i,s,f) for(ll i = s; i < ll(f); i++)
#define inF freopen("input.in", "r", stdin);
#define outF freopen("output.in", "w", stdout);
#define endl '\n'
#define MOD 1000000007
#define mm(arr) memset(arr, 0, sizeof(arr))
#define F first
#define S second
#define int ll

int32_t main(){
    FAST
    int n; cin >> n;
    int arr[n];
    bool deleted[n];
    mm(deleted);
    int mn = 1e9 + 5;
    int ind = 0;
    for(int i = 0; i < n; i++){
        cin >> arr[i];
        if(arr[i] < mn && i != n - 1){
            mn = arr[i];
            ind = i;
        }
    }
    if(n == 1){
        cout << arr[0];
        return 0;
    }
    for(int i = 0; i < n; i++){
        if(arr[i] < 0 && i != ind){
            arr[ind] += arr[i];
            deleted[i] = 1;
        }
    }
    vector<int> newarr;
    for(int i = 0; i < n; i++){
        if(!deleted[i]){
            newarr.pb(arr[i]);
        }
    }
    mm(deleted);
    n = newarr.size();
    int sufMin[n];
    int indSufMin[n];
    sufMin[n - 1] = newarr[n - 1];
    indSufMin[n - 1] = n - 1;
    for(int i = n - 2; i >= 0; i--){
        sufMin[i] = min(sufMin[i + 1], newarr[i]);
        if(sufMin[i] == newarr[i]){
            indSufMin[i] = i;
        }
        else{
            indSufMin[i] = indSufMin[i + 1];
        }
    }
    int last = 0;
    int sum = 0;
    while(last != n){
        for(int j = last; j <= indSufMin[last] - 1; j++){
            deleted[j] = 1;
            sum += newarr[j];
        }
        last = indSufMin[last] + 1;
    }
    for(int i = n - 1; i >= 1; i--){
        if(!deleted[i]){
            newarr[i] += sum;
            break;
        }
    }
    for(int i = n - 1; i >= 1; i--){
        if(!deleted[i]){
            if(arr[i] != 0){
                break;
            }
            else if(arr[i] == 0){
                deleted[i] = 1;
            }
        }
    }
    for(int i = 0; i < n; i++){
        if(!deleted[i]){
            cout << newarr[i] << " ";
        }
    }
    return 0;
}
Copy
a Basilhijaz
GNU G++17
0 ms
508 KB
Wrong Answer