Advertisement
MaskerQwQ

哈夫曼树

Dec 5th, 2022
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.29 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int N=1000;
  6.  
  7. typedef struct HNode{
  8.     char ch;
  9.     int weight;
  10.     HNode *lchild,*rchild;
  11. }*HTree;
  12.  
  13. HTree CreateHuffmanTree(int arr1[],char arr2[],int n){
  14.     HTree forest[N];
  15.     HTree root=NULL;
  16.     for(int i=0;i<n;i++){
  17.         HTree temp;
  18.         temp=(HTree)malloc(sizeof(HNode));
  19.         temp->ch=arr2[i];
  20.         temp->weight=arr1[i];
  21.         temp->lchild=NULL;
  22.         temp->rchild=NULL;
  23.         forest[i]=temp;
  24.     }
  25.  
  26.     for(int i=1;i<n;i++){
  27.         int minn=-1;
  28.         int secminn;
  29.         for(int j=0;j<n;j++){
  30.             if(forest[j]!=NULL&&minn==-1){
  31.                 minn=j;
  32.                 continue;
  33.             }
  34.             if(forest[j]!=NULL){
  35.                 secminn=j;
  36.                 break;
  37.             }
  38.         }
  39.  
  40.         for(int j = secminn;j<n;j++){
  41.             if(forest[j]!=NULL){
  42.                 if(forest[j]->weight<forest[minn]->weight){
  43.                     secminn=minn;
  44.                     minn=j;
  45.                 }else{
  46.                     if(forest[j]->weight<forest[secminn]->weight){
  47.                         secminn=j;
  48.                     }
  49.                 }
  50.             }
  51.        
  52.         }
  53.         root=(HTree)malloc(sizeof(HNode));
  54.         root->weight=forest[minn]->weight+forest[secminn]->weight;
  55.         root->lchild=forest[minn];
  56.         root->rchild=forest[secminn];
  57.  
  58.         forest[minn]=root;
  59.         forest[secminn]=NULL;
  60.     }
  61.     return root;
  62. }
  63.  
  64. void HuffmanCode(HTree root,int len,int arr[]){
  65.     if(root!=NULL){
  66.         if(root->lchild==NULL&&root->rchild==NULL){
  67.             cout<<"字符"<<root->ch<<"的编码为";
  68.             for(int i=0;i<len;i++){
  69.                 cout<<arr[i];
  70.             }
  71.             cout<<endl;
  72.         }
  73.         else{
  74.             arr[len]=0;
  75.             HuffmanCode(root->lchild,len+1,arr);
  76.             arr[len]=1;
  77.             HuffmanCode(root->rchild,len+1,arr);
  78.         }
  79.     }
  80. }
  81. int main(){
  82.     int x;
  83.     cout<<"数据的个数是:";
  84.     cin>>x;
  85.     int num[x];
  86.     char letter[x];
  87.     cout<<"请输入字符和它的权重"<<endl;
  88.     for(int i=0;i<x;i++){
  89.         cin>>letter[i]>>num[i];
  90.     }
  91.     CreateHuffmanTree(num,letter,x);
  92.     HuffmanCode(CreateHuffmanTree(num,letter,x),0,num);
  93.  
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement