1. 程式人生 > >POJ-3253 Fence Repair---Huffman貪心

POJ-3253 Fence Repair---Huffman貪心

https 長度 個數 eof huffman top enc iostream 貪心

題目鏈接:

https://vjudge.net/problem/POJ-3253

題目大意:

有一個農夫要把一個木板鉅成幾塊給定長度的小木板,每次鋸都要收取一定費用,這個費用就是當前鋸的這個木版的長度

給定各個要求的小木板的長度,及小木板的個數n,求最小費用

思路:

HUffman算法

優先隊列

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<queue>
 6 #include<vector>
 7
using namespace std; 8 typedef long long ll; 9 int n; 10 int main() 11 { 12 while(scanf("%d", &n) != EOF) 13 { 14 priority_queue<int, vector<int>, greater<int> >q; 15 int x; 16 for(int i = 0; i < n; i++) 17 { 18 scanf("%d"
, &x); 19 q.push(x); 20 } 21 ll ans = 0; 22 while(q.size() > 1) 23 { 24 int a = q.top(); 25 q.pop(); 26 int b = q.top(); 27 q.pop(); 28 q.push(a + b); 29 ans += (a + b); 30 }
31 cout<<ans<<endl; 32 } 33 return 0; 34 }

POJ-3253 Fence Repair---Huffman貪心