标签:哈夫曼树与优先队列
#include<iostream> #include<stdlib.h> #define N 30000 using 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; else ht[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; }
SDUTOJ 2127 树-堆结构练习——合并果子之哈夫曼树
标签:哈夫曼树与优先队列
原文地址:http://blog.csdn.net/r_misaya/article/details/40789435