Source Code
#include <bits/stdc++.h>
using namespace std;

typedef long long int Long;
const int N = 3e5 + 5;

int n;
pair<Long, int> arr[N];
set<pair<Long, int>> a;

int main() {
  cin >> n;
  Long sum = 0;
  for (int i = 0; i < n; i++) {
    Long x; cin >> x;
    sum += x;
    a.insert({sum, -i});
    arr[i] = {sum, -i};
  }

  vector<Long> ans;
  bool reversed = false;
  int cur = 0;
  Long last = 0;
  while (a.size()) {
    if (a.begin()->first >= 0 && !reversed) {
      vector<pair<Long, int>> ar;
      for (auto it : a) {
        ar.push_back({it.first, -it.second});
      }
      a.clear();
      for (auto it : ar) {
        a.insert(it);
      }
      reversed = true;
    }

    int idx = abs(a.begin()->second);
    a.erase(a.begin());
    ans.push_back(arr[idx].first - last);
    last = arr[idx].first;
    while (cur <= idx) {
      a.erase({arr[cur].first, arr[cur].second});
      a.erase({arr[cur].first, -arr[cur].second});
      ++cur;
    }
  }
  while (ans.size() >= 2 && ans.back() <= 0) {
    Long last = ans.back(); ans.pop_back();
    Long blast = ans.back(); ans.pop_back();
    ans.push_back(last + blast);
  }

  for (long x : ans ) {
    cout << x << " ";
  }

  cout << '\n';
  return 0;
}
Copy
b dauom
GNU G++17
263 ms
27.7 MB
Accepted