
Contents
Problem
中文網址
Solution
利用 Huffman Code 的方法,將較小的數字先行結合成另一個數字,一邊計算其代價。
Code
UVa 10954
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
|
#include<queue> #include<vector> #include<functional> using namespace std;
int () { int n; priority_queue<int, vector<int>, greater<int> > PQ;
while (scanf("%d", &n) && n) { int num; long long sum = 0; for (int i = 0; i < n; i++) { scanf("%d", &num); PQ.push(num); }
for (int i = 1; i < n; i++) { int a, b; a = PQ.top(), PQ.pop(); b = PQ.top(), PQ.pop();
sum += (a + b); PQ.push(a + b); }
PQ.pop(); printf("%lldn", sum); }
return 0; }
|
近期评论