#include <bits/stdc++.h>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define endl "\n"
#define ll long long
#define sz(s) (int)(s.size())
#define INF 0x3f3f3f3f3f3f3f3fLL
#define all(v) v.begin(),v.end()
#define watch(x) cout<<(#x)<<" = "<<x<<endl
const int dr[] { -1, -1, 0, 1, 1, 1, 0, -1 };
const int dc[] { 0, 1, 1, 1, 0, -1, -1, -1 };
#if __cplusplus >= 201402L
template<typename T>
vector<T> create(size_t n) {
return vector<T>(n);
}
template<typename T, typename ... Args>
auto create(size_t n, Args ... args) {
return vector<decltype(create<T>(args...))>(n, create<T>(args...));
}
#endif
void run() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
#else
//freopen("groups.in", "r", stdin);
#endif
}
void solve() {
}
int main() {
run();
int n;
while (cin >> n) {
vector<int> v(n);
for (auto &it : v)
cin >> it;
vector<ll> stk;
vector<int> tmp;
for (int i = 0; i + 1 < n; i++) {
if (v[i] <= 0) {
tmp.push_back(v[i]);
continue;
}
while (stk.size() && stk.back() > v[i]) {
tmp.push_back(stk.back());
stk.pop_back();
}
stk.push_back(v[i]);
}
stk.push_back(v.back());
if (stk.size() >= 3 && stk.back() <= 0) {
stk[0] += stk.back();
stk.pop_back();
}
if (stk.empty())
stk.push_back(0);
sort(all(tmp));
for (auto &it : tmp) {
if (it < 0)
stk[0] += it;
else
stk.back() += it;
}
while (stk.size() >= 2 && stk.back() <= 0) {
stk[0] += stk.back();
stk.pop_back();
}
for (auto &it : stk)
cout << it << ' ';
cout << endl;
}
}
Copy