注释很详细
-1表示不存在
#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;
}