请问这题可否用链表做?我用STL写了一个版本,复杂度不确定是不是O(n)的,附上代码:
#include <cstdio>
#include <list>
using namespace std;
#define N 10000000
#define M 100000 + 1
typedef long long ll;
#define isdigit(x) (x >= '0' && x <= '9')
int a[N];
int cnt[M];
list<ll> lst;
inline int read()
{
char c = getchar();
while (!isdigit(c))
c = getchar();
int x = 0;
while (isdigit(c))
x = x * 10 + c - '0', c = getchar();
return x;
}
int main()
{
int n;
n = read();
for (int i = 0; i < n; i++)
a[i] = read();
for (int i = 0; i < n; i++)
cnt[a[i]]++;
for (int i = 1; i < M; i++)
while (cnt[i])
lst.push_back(i), cnt[i]--;
ll ans = 0;
list<ll>::iterator last = lst.begin();
while (lst.size() > 1)
{
list<ll>::iterator first = lst.begin();
list<ll>::iterator second = lst.begin();
second++;
ll t = *first + *second;
ans += t;
while (t > *last && last != lst.end())
last++;
lst.insert(last, t);
lst.pop_front();
lst.pop_front();
}
printf("%lld\n", ans);
return 0;
}