北大ACM3253 - Fence Repair(赫夫曼编码)

来源:互联网 发布:好听的英文名字 知乎 编辑:程序博客网 时间:2024/06/05 07:07

1.1      算法分析

赫夫曼编码

由于这个问题,考察的是赫夫曼编码,所以优先级队列就直接使用STL的了。

1.2      代码

 

/* * * Introduction : ACM of pku * ID : 3253 * alg : Huffman * Author : Gykimo * Date : 20121203 *  */#include <stdlib.h>#include <stdio.h>#include <queue>using namespace std;struct cmp{bool operator ()(int x, int y){return x > y;}};int planks_num = 0;int *planks = NULL;long long min_amount = 0;void readLine(){scanf("%d", &planks_num);planks = (int *)malloc(planks_num * sizeof(int));for(int i=0; i<planks_num; i++){scanf("%d", planks+i);}}void display(){printf("%lld\n", min_amount);}void huffman(){priority_queue<int, vector<int>, cmp> q(planks, planks+planks_num);int first, second, sum;while(q.size() > 1){first = q.top();q.pop();second = q.top();q.pop();sum = first + second;q.push(sum);min_amount += sum;}}int main(){readLine();huffman();display();return 0;}


1.3      运行结果

 724K 47MS

1.4      总结

主要注意, 结果不能是int,容易过界。

 

原创粉丝点击