哈夫曼树建立与求最短带权路径长度

#include
#include
#define n 7                      //假设有七个节点元素
struct Element
{
    int flag;
    int weight;
    int lchild,rchild,parent;                                   //每个节点均为五元组形式
}huffman[2*n-1];
int min(struct Element huffman[],int k)
{
    int i,p=k-1;
    int min=huffman[k-1].weight;
    for(i=k-2;i>=0;i--)
    {
        if(huffman[i].flag==0)
        {
            if(huffman[i].weight             {
                p=i;
                min=huffman[i].weight;
            }
        }
        else
            continue;
    }
    return p;
}
int min2(struct Element huffman[],int a,int k)
{
    int i,p,q;
    for(i=k-1;i>=0;i--)
    {
        if(huffman[i].flag==0)
            break;
    }
    p=i;
    q=i;
    int min2=huffman[p].weight;
    for(i=p-1;i>=0;i--)
    {
        if((huffman[i].flag==0)&&(i!=a))
        {
            if(huffman[i].weight             {
                q=i;
                min2=huffman[i].weight;
            }
        }
        else
            continue;
    }
    return q;
}
void Hufftree(struct Element huffman[],int w[],int m)
{
    int a,b;
    int i,k;
    for(i=0;i<2*n-1;i++)
    {
        huffman[i].lchild=-1;                       //初始化
        huffman[i].rchild=-1;
        huffman[i].parent=-1;
        huffman[i].flag=0;
    }
    for(i=0;i     {
        huffman[i].weight=w[i];                      //将数组中元素赋给每个节点的权值
    }
    k=7;
    for(k=n;k<2*n-1;k++)
    {
        a=min(huffman,k);                         //找出最小元素
        b=min2(huffman,a,k);                  //找出第二小元素
        huffman[a].parent=k;
        huffman[b].parent=k;
        huffman[a].flag=1;
        huffman[b].flag=1;
        huffman[k].weight= huffman[a].weight+huffman[b].weight;
        huffman[k].lchild=a;
        huffman[k].rchild=b;
    }
    for(i=0;i<13;i++)
    {
          printf("%d ",huffman[i].weight);
    }
    printf("\n");
}
int road(struct Element huffman[],int m)
{
    int h,i,sum=0;
    for(i=0;i     {
        h=depth(huffman,i);
        sum=sum+huffman[i].weight*h;
    }
    return sum;
}
int depth(struct Element huffman[],int i)
{
    int level=0,j=i;
    while(huffman[j].parent>-1)
    {
        level++;
        j=huffman[j].parent;
    }
    return level;
}
main()
{
    int i;
    int length;
    int m=n;
    struct Element huffman[2*n-1]={0};;
    int w[n]={31,16,8,10,11,4,20};
    Hufftree(huffman,w,m);                     //构建哈夫曼树
    length=road(huffman,m);
    printf("带权路径长度为:%d",length);
}

你可能感兴趣的:(哈夫曼树建立与求最短带权路径长度)