首页 > 其他分享 >哈夫曼树哈夫曼编码

哈夫曼树哈夫曼编码

时间:2022-11-25 14:55:48浏览次数:38  
标签:node 编码 哈夫曼 int tt dfs num

#include <bits/stdc++.h>
using namespace std;
const int N=1e3+10;
typedef struct node{
	int w;
	struct node*l;
	struct node*r;
}node;
string s[N*N];
int sum[N*N];
node q[N*N];
int g[N];
int hh=0,tt=-1;
int n;
void dfs(node *u,string str,int num){
	if(!u) return;
	if(!u->l&&!u->r){
		int x=u->w;
		s[x]=str;
		sum[x]=num;
		return;
	}
	dfs(u->l,str+'0',num+1);
	dfs(u->r,str+'1',num+1);
}
bool cmp(node a,node b){
	return a.w<b.w;
}
int main(){
	cin>>n;
	for(int i=0;i<n;i++){
		int x;
		cin>>x;
		g[i]=x;
		q[++tt].w=x;
		q[tt].l=q[tt].r=NULL;
	}
    if(n<=1){
        cout<<"error";
        return 0;
    }
	while(hh<tt){
		node*a,*b;
		sort(q+hh,q+tt+1,cmp);
		a=&q[hh];
		b=&q[hh+1];
		int fa=a->w+b->w;
		q[++tt].w=fa;
		q[tt].l=a,q[tt].r=b;
		hh+=2;
	}
	int res=0;
	dfs(&q[tt],"",0);
	for(int i=0;i<n;i++){
	printf("%d编码为",g[i]);
	cout<<s[g[i]]<<endl;
		res+=sum[g[i]]*g[i];
	}
	cout<<"WPL:"<<res;
}

 

标签:node,编码,哈夫曼,int,tt,dfs,num
From: https://www.cnblogs.com/liyiyang/p/16925127.html

相关文章