1. 程式人生 > >【資料結構--Huffman編碼】優先佇列+棧實現

【資料結構--Huffman編碼】優先佇列+棧實現

#include<bits/stdc++.h>
using namespace std;
typedef struct{
	int weight;
	int id;
	int par,lchild,rchild;
}HTNode,*HuffmanTree;
priority_queue<HTNode> q;
bool operator<(HTNode a,HTNode b){
	return a.weight>b.weight;
}
void createtree(HuffmanTree &HT,int n){
	if(n<=1) return ;
int m; m=2*n-1; HT=new HTNode[1000]; memset(HT,0,sizeof(HT)); for(int i=1;i<=n;i++){ cin>>HT[i].weight; HT[i].id=i; q.push(HT[i]); } int s1,s2; for(int i=n+1;i<=m;i++){ if(q.size()>1){ s1=q.top().id; q.pop(); s2=q.top().id; q.pop(); } HT[s1].par=i; HT[
s2].par=i; HT[i].lchild=s1; HT[i].rchild=s2; HT[i].weight=HT[s1].weight+HT[s2].weight; HT[i].id=i; q.push(HT[i]); } } void hfmc(HuffmanTree HT,int n){ stack<char> HC; for(int i=1;i<=n;i++){ int c=i; int f=HT[i].par; while(f){ if(HT[f].lchild==c) HC.push('0'); else HC.
push('1'); c=f;f=HT[f].par; } cout<<"序號為"<<i<<"的huffman編碼"<<endl; while(!HC.empty()){ cout<<HC.top(); HC.pop(); } puts(""); } } int main(){ int n; cin>>n; HuffmanTree HT; puts("輸入n個節點的權值"); createtree(HT,n); hfmc(HT,n); return 0; }