OJ 赫夫曼編碼

描述

先從鍵盤輸入若干電文所用符號及其出現的頻率,然後構造赫夫曼樹,從而輸出赫夫曼編碼。

注意:爲了保證得到唯一的赫夫曼樹,這裏規定在構造赫夫曼樹時,左孩子結點權值不大於右孩子結點權值,如若有多種選擇,則儘量先選序號偏小的結點。編碼時,左分支取“0”,右分支取“1

輸入3行
第1行:符號個數n(2~20);
第2行:符號,用空格分隔;
第3行:各符號出現頻率(用乘以100後的整數),用空格分隔;輸出各符號對應的赫夫曼編碼。一個符號一行,注意順序。
例如:
a:10
b:110樣例輸入
5
a b c d e
40 20 15 10 15
樣例輸出
a:0
b:111
c:101
d:100
e:110
#include <iostream>
#include "cstring"
#include <stdio.h>
#include "iomanip"
#include "vector"
#include "cmath"
#include "stack"
#include "algorithm"
#include <math.h>
#include "map"
#include "queue"
#include "set"
using namespace std;
int p[1111];
int lon;
struct node
{


    char name;
    int w;
    node *l,*r;
};
bool operator <(node   a,node  b)
{
    return a.w>=b.w;
}
bool dfs(node * r,char s)
{
    if(r->name==s)
        return true;


    if(r->l)
    {
        p[lon++]=0;
        if(dfs(r->l,s))
            return true;
        lon--;
    }
    if(r->r)
    {
        p[lon++]=1;
        if(dfs(r->r,s))
            return true;
        lon--;
    }
    return false;
}
int main()
{
    freopen("a.txt","r",stdin);
    int n;
    cin>>n;
    char str[111111];
    int wei[11111];
    for(int i=0;i<n;i++)
    {
        cin>>str[i];
    }
    for(int i=0;i<n;i++)
    {
        cin>>wei[i];
    }
    priority_queue<node > q;
    node * t;
    for(int i=0;i<n;i++)
    {
        node t;
        t.l=NULL;
        t.r=NULL;
        t.name=str[i];
        t.w=wei[i];
        q.push(t);
    }
    node *a,*b;
    while(q.size()>=2)
    {
        node f=q.top();
        q.pop();
        a=new node;//之所以要用指針是因爲,動態生成 的指針地址是動態的,如果是node 類型 地址是固定的
        a->name=f.name;
        a->l=f.l;
        a->r=f.r;
        a->w=f.w;
        node s=q.top();
        q.pop();
        b=new node;
        b->name=s.name;
        b->l=s.l;
        b->r=s.r;
        b->w=s.w;
        t=new node;
        t->name='*';
        t->w=a->w+b->w;
        t->l=a;
        t->r=b;
        q.push(*t);
    }
      node h=q.top();
      node *start=&h;
      for(int i=0;i<n;i++)
      {
          lon=0;
          dfs(start,str[i]);
          cout<<str[i]<<":";
          for(int j=0;j<lon;j++)
          {
              cout<<p[j];
          }
          cout<<endl;
      }


    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章