#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const int N = 4e5;
ll a[N];
bool ok[N];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i = 0; i < n; i++) {
cin >> a[i];
}
ll sun = 0;
for(int i = n - 1; i >= 0; i--) {
if(a[i] < 0) {
ok[i] = 1;
sun += a[i];
}
}
int idx = 0;
priority_queue<pair<int, int>, vector<pair<int,int>>, greater<>> pq;
for(int i = 0; i < n - 1; i++) {
if(!ok[i]) {
pq.push({a[i], i});
}
}
while(pq.size()) {
pair<int, int> u = pq.top();
pq.pop();
if(!ok[u.second]) {
for(; idx < u.second; idx++) {
if(!ok[idx]) {
a[n - 1] += a[idx];
ok[idx] = 1;
}
}
idx = u.second + 1;
}
}
vector<int> ans;
for(int i = 0; i < n; i++) {
if(!ok[i])
ans.push_back(a[i]);
}
while(ans.size()) {
if(ans.back() == 0) ans.pop_back();
else break;
}
for(auto x : ans) {
cout << x << ' ';
}
}
Copy