#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define sz(s) (int)(s.size())
#define endl "\n"
#define BI acos(-1)
#define all(a) a.begin(), a.end()
void Open() {
#ifndef ONLINE_JUDGE
#endif !ONLINEJUDGE
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
}
int dx[]{ 1, -1, 0, 0, 1, 1, -1, -1 };
int dy[]{ 0, 0, 1, -1, 1, -1, 1, -1 };
const int OO = 0x3f3f3f3f;
int main()
{
Open();
int n;
cin >> n;
vector<ll>a(n), b,c;
map<ll, int>mp;
vector<ll>sor;
ll s_n = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
if (a[i] < 0)
s_n += a[i];
}
bool p = 1;
for (int i = 0; i < n; i++)
{
if (a[i] < 0)
{
if (p) {
sor.push_back(s_n);
b.push_back(s_n);
mp[s_n]++;
p = 0;
}
}
else
{
if (!mp[a[i]])
sor.push_back(a[i]);
b.push_back(a[i]);
mp[a[i]]++;
}
}
//for (auto it : b)cout << it << ' ';
//cout << endl;
sort(all(sor));
reverse(all(sor));
ll s = 0;
for (int i = 0; i < sz(b)-1; i++)
{
while (!sor.empty()&&mp[sor.back()] == 0)
{
sor.pop_back();
}
if (b[i] != sor.back())
{
s += b[i];
mp[a[i]]--;
}
else
{
c.push_back(b[i]);
mp[b[i]]--;
}
}
for (auto it : c)cout << it << ' ';
cout << b.back() + s;
}
Copy