哈夫曼樹的建立及求wpl
阿新 • • 發佈:2019-02-10
#include<stdio.h> #include<iostream> #include<string.h> #include<queue> using namespace std; #define maxn 100 struct node { int v,f,ls,rs; }tree[4*maxn]; int num;//num表示總節點個數 int judge() { int sum=0; for(int i=0;i<num;i++) { if(tree[i].f==-1) sum++; if(sum==2) return 1; } return 0; } void bfs(int*p) { queue<struct node>q; int i=0; while(!q.empty()) q.pop();//清空佇列 while(tree[i].f!=-1) i++;//找根節點的位子 q.push(tree[i]); for(int depth=1;1;depth++) { int t=q.size();//t表示哈夫曼樹中深度為depth的節點的數量 if(t==0) return ;//t等於0時,哈夫曼樹每一層所有節點都遍歷過了 while(t--) { struct node now=q.front(); q.pop(); if(now.ls==-1&&now.rs==-1) { *p+=(depth-1)*now.v; } else { if(now.ls!=-1) q.push(tree[now.ls]); if(now.rs!=-1) q.push(tree[now.rs]); } } } } int main() { int ans=0;//帶權路徑長度 int index1,index2; cin>>num; memset(tree,-1,sizeof(tree)); for(int i=0;i<num;i++) cin>>tree[i].v; while(judge())//judge函式用於判斷哈夫曼樹是否已經完成建立 { int i=0; index1=-1; index2=-1; while(tree[i].f!=-1) i++; index1=i; for(i++;i<num;i++) { if(tree[i].f==-1) { if(tree[index1].v>tree[i].v) { index2=index1; index1=i; } else { if(index2==-1) index2=i; else if(tree[index2].v>tree[i].v) index2=i; } } } tree[num].v=tree[index1].v+tree[index2].v; tree[num].ls=index1; tree[num].rs=index2; tree[index1].f=num; tree[index2].f=num; num++; } for(int i=0;i<num;i++) cout<<"index:"<<i<<" node value:"<<tree[i].v<<" ls:"<<tree[i].ls<<" rs:"<<tree[i].rs<<" f:"<<tree[i].f<<endl; bfs(&ans);//求解wpl cout<<"wpl:"<<ans<<endl; return 0; }