哈夫曼树

来源:互联网 发布:淘宝降权 编辑:程序博客网 时间:2024/04/28 18:50
题目描述:

哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。

输入:

输入有多组数据。
每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。

输出:

输出权值。

样例输入:
5  1 2 2 5 9
样例输出:
37
提示:
来源:

2010年北京邮电大学计算机研究生机试真题


这题目拿上来想法太多了,搞得没细想就开始做,得以下经验:

1. 遇到树类问题,最好不用优先队列而是用数组模拟,因为优先队列操作对象比较方便,而操作指针不方便。

2. 树中指针问题。若queue设计为queue<Tree*> Q,则Tree *r=Q.top(); Q.pop();后,r的内容会变为现在Q.top()的内容。所以尽量不在队列中用指针。

#include "iostream"#include "stdio.h"#include "math.h"#include "vector"#include "queue"#include "memory.h"#include "algorithm"#include "string"using namespace std;int n;struct Tree{struct Tree *l,*r;int x;bool leaf;bool used;Tree(){l=r=NULL;used=false;}};Tree *Q[10010];int cnt;int Dfs(Tree *r,int level){if(r->leaf)return r->x*level;return Dfs(r->l,level+1)+Dfs(r->r,level+1);}Tree* Select(bool *emptyflag){int minn=100*1001;//n<=100,每个数的权值<=1000,所以队列Q中每个节点的x<=100*1000int k=-1;for(int i=0;i<cnt;i++)if(!Q[i]->used&&Q[i]->x<minn){minn=Q[i]->x;k=i;}if(k!=-1){Q[k]->used=true;return Q[k];}else{*emptyflag=true;return NULL;}}int main(){while(scanf("%d",&n)!=EOF){int i,j,x;Tree *temp,*q1,*q2;cnt=0;for(i=0;i<n;i++){scanf("%d",&x);q1=new Tree;q1->x=x;q1->leaf=true;Q[cnt++]=q1;}if(n==1){printf("%d\n",x);continue;}bool empty=false;while(true){q1=Select(&empty);q2=Select(&empty);if(empty)break;temp=new Tree;temp->l=q1;temp->r=q2;temp->leaf=false;temp->x=q1->x+q2->x;Q[cnt++]=temp;}printf("%d\n",Dfs(q1,0));}}


原创粉丝点击