• huffman


    #include <bits/stdc++.h>
    using namespace std;
    const int maxn=1e5+7;
    const int INF=0x3f3f3f3f;
    struct Huffman_Node{
       int ans;
       int father;
       int left;
       int right;
    }H_Node[maxn];  
    int n;
    void init()///初始化
    {
       for (int i=0;i<(n+n-1);++i)
       {
         H_Node[i].father = -1;
         H_Node[i].left = -1;
         H_Node[i].right = -1;
       }
    }
    int H[maxn];
    int main()
    {
      scanf("%d",&n);
      init();
      memset(H,-1,sizeof(H));
      for(int i=0;i<n;++i)
      {
        scanf("%d",&H_Node[i].ans);
      }
      for (int j=1;j<n;++j)///n个叶子节点,最多合并n-1次
      {
        int m1 = INF;///最小的数
        int m2 = INF;///第二小的数
        int idx_1 = -1;
        int idx_2 = -1;
          for (int t=0;t<n+j-1;++t)
          {
            ///cout<<"fa"<<' '<<H_Node[t].father<<endl;
             if (H_Node[t].father==-1)
             {
                if (H_Node[t].ans < m1)
                {
                   idx_2 = idx_1;
                   idx_1 = t;
                   m2 = m1;
                   m1 = H_Node[t].ans;
                }
                else if (H_Node[t].ans < m2)
                {
                   m2 = H_Node[t].ans; 
                   idx_2 = t;
                }
             }
          }
          /// cout<<idx_1<<' '<<idx_2<<endl;
          H_Node[n+j-1].ans = H_Node[idx_1].ans + H_Node[idx_2].ans;///合并概率
          ///cout<<H_Node[n+j-1].ans<<endl;
          H_Node[idx_2].father = n+j-1;
          H_Node[idx_1].father = n+j-1;
          H_Node[n+j-1].left = idx_1;
          H_Node[n+j-1].right = idx_2;
      }
      for (int i=0;i<n;++i)
      {
         int F=H_Node[i].father;
         ///cout<<F<<endl;
         int C=i;
         int cnt = n;
         while (F != -1)
         {
           if (H_Node[F].left==C)
           {
              H[--cnt]=0;
              ///cout<<0;
           }
           else 
           {
              H[--cnt]=1;
              ///cout<<1;
           }
           C = F;
           F = H_Node[F].father;
         }
         for (int j=cnt;j<n;++j)
         {
           printf("%d",H[j]);
         }
         puts("");
      }
      return 0;
    }
    
    齐芒行,川锋明!
  • 相关阅读:
    BigInteger实现除法取余
    BigDecimal介绍及BigDecimal实现四舍五入
    Jenkins的凭证管理
    Adapter(适配器)-类对象结构型模式
    singleton(单件)-对象创建型模式
    ProtoType(原型)-对象创建型模式
    Factory Method(工厂方法)-对象创建型模式
    Builder(生成器)-对象创建型模式
    Abstract Factory(抽象工厂)模式
    设计模式-序
  • 原文地址:https://www.cnblogs.com/qimang-311/p/13814846.html
Copyright © 2020-2023  润新知