SDUTOJ 2127 树-堆结构练习——合并果子之哈夫曼树
来源:互联网 发布:程序员证书有哪些 编辑:程序博客网 时间:2024/05/20 21:42
#include<iostream>#include<stdlib.h>#define N 30000using namespace std;int a[N+1],o=0;typedef struct {int weight;int parent,lchild,rchild;}htnode;typedef struct{int weight;}htcode;void huffmanselect(htnode ht[],int k,int *s1,int *s2)//挑选所给结点两个最小的.{int i;for(i=1;i<=k && ht[i].parent!=0;i++){;;}*s1=i; for(i=1;i<=k;i++){if(ht[i].parent==0 && ht[i].weight<ht[*s1].weight)*s1=i;}for(i=1;i<=k;i++){if(ht[i].parent==0 && i!=*s1)break;}*s2=i;for(i=1;i<=k;i++){if(ht[i].parent==0 && ht[i].weight<ht[*s2].weight && i!=*s1)*s2=i;}}void huffmantree(htnode ht[],htcode hc[],int n)//构建哈夫曼树{int i,m,s1,s2;m=2*n-1;for(i=1;i<=m;i++){if(i<=n)ht[i].weight=hc[i].weight;elseht[i].parent=0; ht[i].parent=ht[i].lchild=ht[i].rchild=0;}for(i=n+1;i<=m;i++){huffmanselect(ht,i-1,&s1,&s2);ht[s1].parent=i;ht[s2].parent=i;ht[i].lchild=s1;ht[i].rchild=s2;ht[i].weight=ht[s1].weight+ht[s2].weight;a[o++]=ht[i].weight;//将每一次构造出的根存在数组中}}int main(){int n,i,j,s=0;htnode ht[N+1];htcode hc[N+1];cin>>n;for(i=1;i<=n;i++){cin>>hc[i].weight;}huffmantree(ht,hc,n); for(j=0;j<o;j++){ s+=a[j];}cout<<s<<endl;return 0;}//第一种方法:哈夫曼树//第二种方法:优先队列的使用#include<stdio.h>#include<queue>#include<algorithm>using namespace std;int main(){int num;int n,i,a;priority_queue<int>plank;//<优先队列的使用>从小到大的顺序优先级队列long long int sum;while(scanf("%d",&n)!=EOF){sum=0;while(n--){scanf("%d",&num);plank.push(-num);}while(plank.size()!=1){a=plank.top();plank.pop();a+=plank.top();sum+=a;plank.pop();plank.push(a);}plank.pop();printf("%lld\n",-sum);}return 0;}
2 0
- SDUTOJ 2127 ——树-堆结构练习——合并果子之哈夫曼树 优先队列
- SDUTOJ 2127 树-堆结构练习——合并果子之哈夫曼树 【STL】
- SDUTOJ 2127 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 树-堆结构练习——合并果子之哈夫曼树
- 安卓学习记录(一)activity间信息交互的四种方式
- QEMU KVM libvirt 手册(1): 安装
- C++primer(第五版)第三章字符串、向量和数组学习笔记1(string包含C++11特性及部分习题解答)
- finally执行
- 测试中的几个原则(未完待续)
- SDUTOJ 2127 树-堆结构练习——合并果子之哈夫曼树
- LeetCode Maximum Depth of Binary Tree
- 欧几里得算法及扩展欧几里得算法
- LINK fatal error LNK1123
- 科臃乒庸炕安浇幸负延焦苛棺杉崩
- 第10周项目2-M$pszi$y是什么意思
- ubuntu 12.04 安装 GMA3650驱动
- 透匆衬滩彼郧屠谱秦甭仁胖以荣胖
- 修改android studio sdk路径