哈夫曼编码(2)
这里是一道模板题
B2168 哈夫曼编码
题目含义:
给定\(n\)个单词\(s_i\),及其出现频率\(w_i\)
对单词进行哈夫曼编码
输出单词顺序与输入一致
思路:
哈夫曼建树
dfs求出叶节点01编码串
注意:
- 总节点数\(2n-1\)
- 权值求和,考虑用
long long
代码:
const ll N=2e3+5;
struct node{ll w,idx;};
struct cmp{
bool operator()(const node& nd1,const node& nd2){
return nd1.w>nd2.w;//后者向上
}
};
priority_queue<node,vector<node>,cmp> pq;
string str[N];
string ans[N];
ll w[N],l[N],r[N];
ll cnt;
//对于初始节点,存到1-n
//之后节点由++cnt得到编号
//l[i],r[i]标识i左右孩子的编号
void dfs(ll root,string& s)
{
if(!l[root]&&!r[root]){
ans[root]=s;
return;
}
//左儿子
s.push_back('0');
dfs(l[root],s);
s.pop_back();
//右儿子
s.push_back('1');
dfs(r[root],s);
s.pop_back();
}
int main()//建树-编码
{
ios::sync_with_stdio(0),cin.tie(0);
ll n; cin>>n;
for(ll i=1;i<=n;++i){
cin>>str[i]>>w[i];
if(n==1){cout<<str[i]<<" "<<"0"<<endl;return 0;}
++cnt;
pq.push({w[i],i});
l[i]=0; r[i]=0; //叶子节点
}
while(pq.size()>1){
node first=pq.top(); pq.pop();
node second=pq.top(); pq.pop();
++cnt;
pq.push({first.w+second.w,cnt});
//cerr<<first.w+second.w<<","<<cnt<<endl;
l[cnt]=first.idx; r[cnt]=second.idx;
}
string s;
dfs(cnt,s);
for(ll i=1;i<=n;++i){
cout<<str[i]<<" "<<ans[i]<<"\n";
}
return 0;
}

浙公网安备 33010602011771号