Source Code
#include <bits/stdc++.h>
using namespace std;
    
int main (){

  #ifndef ONLINE_JUDGE
    freopen("SuhaibSawalha1","r",stdin);
  #endif

  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  int n;
  cin >> n;
  long long neg = 0, pos = 0;
  int idx = -1, last, first_neg = -1;
  set<array<int, 2>> s;
  for (int i = 0; i < n; ++i) {
    int x;
    cin >> x;
    if (x < 0) {
      neg += x;
      if (first_neg == -1) {
        first_neg = i;
      }
    }
    else {
      s.insert({x, i});
      last = i;
    }
  }
  vector<pair<long long, int>> a;
  for (auto e : s) {
    if (e[1] > idx) {
      idx = e[1];
      a.push_back({e[0], e[1]});
    }
    else {
      pos += e[0];
    }
  }
  if (a.empty()) {
    return !(cout << neg);
  }
  if (neg && first_neg < a[0].second) {
    a.insert(a.begin(), {neg, 0});
  }
  else {
    a[0].first += neg;
  }
  if (idx == last) {
    a.back().first += pos;
  }
  else {
    a.push_back({pos, 0});
  }
  while (a.size() && !a.back().first) {
    a.pop_back();
  }
  if (a.empty()) {
    return !(cout << 0);
  }
  for (auto i : a) {
    cout << i.first << " ";
  }

  return 0;
}
Copy
a SuhaibSawalha1
GNU G++17
0 ms
848 KB
Wrong Answer