哈夫曼树

不容易qwq~~

终于写出来了(但是也不知道对不对)~~

表示纯手打 (*^▽^*)yeah~~

代码能力又得到提升了呢!

#include<bits/stdc++.h>
using namespace std;

struct node{
    int f,l,r;
    char v;
    int w;
    int order;
}t[1020000];

struct n{
    int s,bit[100];
}hf[1020];


int n;
priority_queue<node> pq;
bool operator < (const node & a,const node & b)
{
    return a.w>b.w;
}
int u;

void build()
{
    while(n<2*u-1)
    {
        while(pq.top().f!=-1)
        {
            pq.pop();
        }
        
        node a=pq.top();pq.pop();
        
        while(pq.top().f!=-1)
        {
            pq.pop();
        }
        
        node b=pq.top();pq.pop();
        if(b.v =='0'&&a.v !='0'&&a.w ==b.w ) 
        {
            node c;
            c=a;
            a=b;
            b=c;
         } 
        
        /*if(a.v =='a'||b.v =='a')
        {
            cout<<a.v <<" "<<b.v <<'\n';
        }*/
        
        
        n++;
        t[n].order =n;
        t[n].f=-1;
        t[n].l =a.order ;
        t[n].r =b.order ;
        t[n].w =a.w +b.w ;
        a.f = n;
        b.f =n;
        t[a.order ]=a;
        t[b.order ]=b;
        pq.push(t[n]);
//        cout<<t[n].order <<" l: "<<t[n].l <<" r:"<<t[n].r <<" "<<t[n].w <<'\n';
    }
}

int main()
{
    cin>>n;
    u=n;
    
    for(int i=1;i<=2*n;i++)
    {
        t[i].v ='0';
    }
    
    for(int i=1;i<=n;i++)
    {
        cin>>t[i].v >>t[i].w ;
        t[i].order =i;
        t[i].f =t[i].l =t[i].r =-1;
        pq.push(t[i]);
    }
    
    
    /*for(int i=1;i<=n;i++) {
        node p=pq.top();
        cout<<p.w <<" "<<p.f <<" \n";
        pq.pop();
    }
    return 0;*/
    
    build();
    
    for(int i=1;i<=n;i++)
    {
        hf[i].s =0;
    }
    
    for(int i=1;i<=n;i++)
    {
        int fa;
        node now;
        now=t[i];
        int ord=i;
        while(now.f !=-1)
        {
            fa=now.f ;
//            cout<<fa<<" fa\n";
            if(ord==t[fa].l ) 
            {
    //            hf[i].s =0;
                hf[i].s ++;
                hf[i].bit [hf[i].s ]=0;
            }
            
            else if(ord==t[fa].r )
            {
                hf[i].s ++;
                hf[i].bit [hf[i].s ]=1;
            }
            now=t[fa];
            ord=fa;
        }
        
    }
    
    for(int i=1;i<=u;i++)
    {
        cout<<t[i].v <<" :";
        int m=hf[i].s ;
        for(int j=m;j>=1;j--) cout<<hf[i].bit[j]<<" ";
        cout<<'\n'; 
    }
    
    /*for(int i=1;i<=n;i++)
    {
        cout<<t[i].f <<" "<<t[i].l <<" "<<t[i].r <<" "<<t[i].order 
        <<" "<<t[i].v <<" "<<t[i].w <<'\n';
    }*/
    
    return 0;
}

/*
5
a 12
b 56
c 10
d 78
f 2
*/

 

posted @ 2020-12-14 17:13  yxr~  阅读(109)  评论(0编辑  收藏  举报