zoukankan      html  css  js  c++  java
  • 哈夫曼树建立 皇星客栈

    View Code
     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<iostream>
     4 #define MAXVALUE 100                //定义最大权值
     5 #define MAXLEAF 50                  //定义哈夫曼树中叶子节点个数
     6 #define MAXNODE MAXLEAF*2-1
     7 
     8 typedef struct{
     9     int weight;
    10     int parent;
    11     int lchild;
    12     int rchild;
    13     }HNodeType;
    14     
    15 static int n; 
    16 
    17 HNodeType HuffNode[MAXNODE];
    18 HNodeType *HaffmanTree( ){
    19     int i,j,m1,m2,x1,x2;
    20     scanf("%d",&n);                     //输入叶子节点个数
    21     for(i=0;i<2*n-1;i++)          //数组HuffNode[ ]初始化
    22     {
    23         HuffNode[i].weight=0;
    24         HuffNode[i].parent=-1;
    25         HuffNode[i].lchild=-1;
    26         HuffNode[i].rchild=-1;
    27     }
    28     for(i=0;i<n;i++)
    29             scanf("%d", &( HuffNode[i].weight));
    30     for(i = 0 ; i < n - 1 ; i++ ) {
    31      m1=m2=MAXVALUE;
    32      x1 = x2 = 0;
    33      for( j=0 ; j < n + i ; j++ )  
    34      {
    35          if(HuffNode[j].parent == -1 && HuffNode[j].weight < m1)
    36          {   
    37              m2 = m1;
    38              x2 = x1;
    39              m1 = HuffNode[j].weight;
    40              x1 = j;
    41          }
    42          else
    43             if(HuffNode[j].parent == -1 && HuffNode[j].weight < m2 ){
    44                m2 = HuffNode[j].weight;                                                                            
    45                x2 = j;
    46             }
    47     }
    48     HuffNode[x1].parent = n + i;
    49     HuffNode[x2].parent = n + i;
    50     HuffNode[n+i].weight = HuffNode[x1].weight + HuffNode[x2].weight;
    51     HuffNode[n+i].lchild = x1;
    52     HuffNode[n+i].rchild = x2;
    53   }
    54   return HuffNode;
    55 }
    56 
    57 int main( )
    58 {
    59      HaffmanTree( );
    60      for(int i=0; i < 2*n-1 ; i++)
    61      {
    62          printf("%d ",HuffNode[i].weight);
    63          printf("%d ",HuffNode[i].lchild);
    64          printf("%d ",HuffNode[i].rchild);
    65          printf("%d",HuffNode[i].parent);
    66          printf("\n");
    67      }
    68      return 0;
    69 }
    70     
    71     
    72     
  • 相关阅读:
    一、异常
    自控力_第三章
    Vocabulary Recitation 2020/05/05
    Vocabulary Recitation 2020/05/04
    Vocabulary Recitaion 2020/05/03
    Vocabulary Recitation 2020/05/01
    最大子序列和
    Vocabulary Recitation 2020/04/29
    自控力_第二章
    Vocabulary Recitation 2020/04/27
  • 原文地址:https://www.cnblogs.com/huangxingkezhan/p/2782161.html
Copyright © 2011-2022 走看看