难度:3
用优先队列很好做,书上的n方的做法没有看。
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
int main() {
int n;
cin >> n;
priority_queue<int, vi, greater<int> > q;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
q.push(x);
}
int ans = 0;
while (q.size() >= 2) {
int t1 = q.top(); q.pop();
int t2 = q.top(); q.pop();
ans += t1 + t2;
q.push(t1 + t2);
}
cout << ans;
return 0;
}