-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProblemD.cpp
65 lines (61 loc) · 1.54 KB
/
ProblemD.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<cstdio>
int ans, n;
class Heap {
private:
int heap[1005], size;
public:
Heap() : size(0) {}
void pop() {
heap[1] = heap[size--];
int now = 1;
while(now * 2 <= size) {
int next = now * 2;
if(next + 1 <= size && heap[next] > heap[next + 1]) next++;
if(heap[now] > heap[next]) {
int temp = heap[now];
heap[now] = heap[next];
heap[next] = temp;
now = next;
}
else break;
}
}
int top() {
return heap[1];
}
void push(int x) {
heap[++size] = x;
int now = size;
while(now > 1) {
int next = now / 2;
if(heap[now] < heap[next]) {
int temp = heap[now];
heap[now] = heap[next];
heap[next] = temp;
now = next;
}
else break;
}
}
};
int main() {
int T;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
Heap h; ans = 0;
for(int i = 0; i < n; i++) {
int tmp;
scanf("%d", &tmp);
h.push(tmp);
}
for(int i = 0; i < n - 1; i++) {
int x = h.top(); h.pop();
int y = h.top(); h.pop();
ans += x + y;
h.push(x + y);
}
printf("%d\n", ans);
}
return 0;
}