跳到正文

算法·理论

哈夫曼编码

plant_me约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年7月5日
收录
2026年7月5日
更新
2026年11月21日
篇幅
约 3 分钟
获赞
1

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int a[100005],n,ans;
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q;
pair<int,int> tre[200005];
vector<int> v;
vector<pair<int,string> > res;
void dfs(int x,int k){
    if(tre[x].first==0&&tre[x].second==0){
        int val=a[x];
        string code;
        for(int num:v) code+=char(num+'0');
        res.emplace_back(val,code);
        ans+=k*val;
        return;
    }
    if(tre[x].first!=0){
        v.push_back(0);
        dfs(tre[x].first,k+1);
        v.pop_back();
    }
    if(tre[x].second!=0){
        v.push_back(1);
        dfs(tre[x].second,k+1);
        v.pop_back();
    }
}
signed main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        q.push({a[i],i});
    }
    int nodecnt=n;
    int rootid=0;
    while(q.size()>1){
        auto p1=q.top();
		q.pop();
        auto p2=q.top();
		q.pop();
        int w1=p1.first,id1=p1.second;
        int w2=p2.first,id2=p2.second;
        nodecnt++;
        int newid=nodecnt;
        if(w1<=w2){
            tre[newid].first=id1;
            tre[newid].second=id2;
        }else{
            tre[newid].first=id2;
            tre[newid].second=id1;
        }
        q.push({w1+w2,newid});
    }
    rootid=q.top().second;
    dfs(rootid,0);
    sort(res.begin(),res.end());
    cout<<"权值    哈夫曼编码\n";
    for(auto &p:res){
        cout<<setw(5)<<p.first<<"  "<<p.second<<'\n';
    }
    cout<<"总带权路径长度= "<<ans<<endl;
    return 0;
}
原文