wpl计算方法_计算哈弗曼树的WPL值

NO COPYING!

NO COPYING!

NO COPYING!

//Sinhaeng Hhjian

#include

#define inf 0x3f3f3f3f

#define MAX 100

using namespace std;

const int maxn=1005;

struct node{

int num, v, f, ls, rs;

}tree[4*maxn];

int st[maxn];

struct Queue{

node *base;

int f, r;

};

void InitQueue(Queue &q){

q.base = (node *)malloc(sizeof(node) * MAX);

q.f = q.r = 0;

}

void InQueue(Queue &q, node bt){

q.base[q.r++] = bt;

}

int IsEmpty(Queue q){

return q.f == q.r? 1:0;

}

void OutQueue(Queue &q, node &bt){

if(IsEmpty(q)) return ;

bt = q.base[q.f++];

}

int judge(int n){

int sum=0;

for(int i=0;i

if(tree[i].f==-1)

sum++;

if(sum==2)

return 1;

}

return 0;

}

int bfs(int n){

int ans=0;

Queue q;

InitQueue(q);

InQueue(q, tree[n-1]);

for(int dep=1;;dep++){

int t=q.r-q.f;

if(t==0) return ans;

while(t--){

node bt;

OutQueue(q, bt);

if(bt.ls==-1 && bt.rs==-1){

ans+=(dep-1)*bt.v;

st[bt.num]=(dep-1)*bt.v;

}

else{

if(bt.ls!=-1)

InQueue(q, tree[bt.ls]);

if(bt.rs!=-1)

InQueue(q, tree[bt.rs]);

}

}

}

}

int main(){

int ans=0, num1, num2, n;

printf("请输入点的个数:");

scanf("%d", &n);

int nn=n;

memset(tree,-1,sizeof(tree));

printf("请输入每个点的权值:");

for(int i=0;i

tree[i].num=i;

scanf("%d", &tree[i].v);

}

while(judge(n)){

num1=num2=0;

int flag=0;

for(int i=0;i

if(tree[i].f==-1){

if(flag==0){

flag=1;

num1=i;

}

if(tree[i].v

num1=i;

}

tree[num1].f=n;

flag=0;

for(int i=0;i

if(tree[i].f==-1){

if(flag==0){

flag=1;

num2=i;

}

if(tree[i].v

num2=i;

}

tree[num2].f=n;

tree[n].v=tree[num1].v+tree[num2].v;

tree[n].ls=num1;

tree[n++].rs=num2;

}

ans = bfs(n);

printf("每个叶子结点的带权路径长度:\n");

for(int i=0;i

printf("%d(权值为%d):%d\n", i, tree[i].v, st[i]);

printf("哈夫曼树的WPL值为:%d\n", ans);

return 0;

}

你可能感兴趣的:(wpl计算方法)