提交时间:2024-03-09 11:14:11

运行 ID: 136628

#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 005; int heap[N], cnt; int d2u(int cur) { int fa = cur / 2; if (fa > 0 && heap[fa] > heap[cur]) { swap(heap[fa], heap[cur]); return d2u(fa); } return cur; } int ins(int x) { heap[++cnt] = x; return d2u(cnt); } void u2d(int cur) { int l = 2 * cur, r = l + 1; if (r <= cnt && heap[l] > heap[r]) swap(l, r); if (l <= cnt && heap[cur] > heap[l]) { swap(heap[cur], heap[l]); u2d(l); } } void del() { swap(heap[1], heap[cnt]); --cnt; u2d(1); } int main() { int n, s = 0; cin >> n; for (int i = 1, x; i <= n; i++) cin >> x, ins(x); while (cnt >= 2) { int tmp = heap[1]; del(); int tmp1 = heap[1]; del(); ins(tmp + tmp1); s += tmp + tmp1; } cout << s << endl; return 0; }