Exploring in The Art Of Programming about Huffman Tree's Creation.

Exploring in The Art Of Programming about Huffman Tree's Creation.

 

/**/ /*数据结构作业之——哈弗曼树的构造以及WPL的计算;
给出叶子结点的权值,然后求出其WPL 
程序中出现的叶子结点均为正数,并以0结束
*/

// Get Guidance By Mr ZhangHong
// Student: abilitytao

#include
< iostream >
#include
< cmath >
#include
< cstring >
using   namespace  std;
#define  MAX 10000000

struct  node 
{
    
int w;
    
int p;
    
int lch;
    
int rch;
}
huffman[MAX];




int  search_min( int  l, int  r)
{

    
int min=999999999;
    
int mark=0;
    
int i;
    
for(i=l;i<=r;i++)
    
{
        
if(huffman[i].w<min&&huffman[i].p==0)
        
{
            min
=huffman[i].w;
            mark
=i;
        }

    }

    
return mark;
    
}


int  search_second_min( int  l, int  r)
{
    
int min=search_min(l,r);
    
int secondmin=999999999;
    
int mark=0;
    
int i;
    
for(i=l;i<=r;i++)
    
{

        
if(huffman[i].w>=huffman[min].w&&huffman[i].w<=secondmin&&huffman[i].p==0&&i!=min)
        
{
            secondmin
=huffman[i].w;
            mark
=i;
            
        }


    }

    
return mark;
}


int  main()
{

    
int n;
    
int i;
    
int num;
    
for(i=1;;i++)
    
{

        scanf(
"%d",&n);
        huffman[i].w
=n;
        huffman[i].p
=0;
        huffman[i].lch
=0;
        huffman[i].rch
=0;
        
if(n==0)
            
break;
    }

    num
=i-1;

    
int pos=num;
    
for(i=1;i<=num-1;i++)
    
{
        
int max_mark=search_min(1,i+num-1);
        
int secondmax_mark=search_second_min(1,i+num-1);
        
++pos;
        huffman[pos].w
=huffman[max_mark].w+huffman[secondmax_mark].w;
        huffman[pos].p
=0;
        huffman[pos].lch
=secondmax_mark;
        huffman[pos].rch
=max_mark;
        huffman[max_mark].p
=pos;
        huffman[secondmax_mark].p
=pos;
    }

    printf(
"这棵树的WPL为:%d\n",huffman[pos].w);
    system(
"pause");
    
return 0;
}





你可能感兴趣的:(Exploring in The Art Of Programming about Huffman Tree's Creation.)