poj3253Fence Repair(贪心,哈夫曼编码)

来源:互联网 发布:js style.display 编辑:程序博客网 时间:2024/05/27 00:49

题意

有一块木板,要把它切成长度指定的n块 ,每次切断时需要付出这块木板长度的代价,问最少要付出多少代价

思路

这题切割可以用二叉树表示出来,这样很显然能看出切的次数越多,在树中的深度越深。切的次数越多,显然被计数的(即付出代价)次数越多,那么显然越深的地方木板长度应该越小,以此来构建二叉树。即每次取出最小的两个作为叶子节点。

#include <cstdio>#include <iostream>#include <queue>#define ll long longusing namespace std;const int kMaxn = 20000 + 10;int main() {    int n;    while(~scanf("%d", &n)) {        priority_queue<int, vector<int>, greater<int> >Q;        for(int i = 1; i <= n; i++) {            int x;            scanf("%d", &x);            Q.push(x);        }           ll ans = 0;        while(!Q.empty()) {            int l1 = Q.top();            Q.pop();            if(Q.empty())                break;            int l2 = Q.top();            Q.pop();            int l = l1 + l2;            ans += l;            Q.push(l);        }        printf("%lld\n", ans);    }    return 0;}
0 0
原创粉丝点击