https://vjudge.net/problem/UVA-10954
題意:有n個數的集合S,每次可以從S中刪除兩個數,然后把它們的和放回集合,直到剩下一個數。每次操作的開銷等于刪除的兩個數之和,求最小開銷。
思路:Huffman編碼。
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 5 struct cmp 6 { 7 bool operator()(const int a, const int b) const 8 { 9 return a > b; 10 } 11 }; 12 13 int main() 14 { 15 //freopen("D:\\txt.txt", "r", stdin); 16 int n; 17 while (cin >> n && n) 18 { 19 priority_queue<int,vector<int>,cmp> q; 20 int ans = 0, a; 21 for (int i = 0; i < n; i++) 22 { 23 cin >> a; 24 q.push(a); 25 } 26 for (int i = 0; i < n - 1; i++) 27 { 28 int b = q.top(); q.pop(); 29 int c = q.top(); q.pop(); 30 q.push(b + c); 31 ans += b + c; 32 } 33 cout << ans << endl; 34 } 35 return 0; 36 }
?