// stringtraining.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 50;
struct hnode
{
string code;
int bit;
int v;
int left, right;
int num;
void init(int q)
{
v = q;
left = -1;
right = -1;
bit = -1;
}
bool operator<(const hnode &oth)const
{
return v>oth.v;
}
}huffman[maxn];
int tot = 0;
map<int, char>mp;
int n;
void getcode(int t, string s)
{
string codet;
codet += s;
if (huffman[t].left == -1 && huffman[t].right == -1)
{
huffman[t].code += s;
return;
}
if (huffman[t].left != -1)
{
string m1 = codet + "0";
getcode(huffman[t].left, m1);
huffman[t].code += s;
}
if (huffman[t].right != -1)
{
string m2 = codet + "1";
getcode(huffman[t].right, m2);
huffman[t].code += s;
}
return;
}
int main()
{
scanf("%d", &n);
priority_queue<hnode>pq;
for (int i = 1; i <= n; i++)
{
char ch;
int v;
cin >> ch >> v;
mp[i] = ch;
huffman[i].init(v);
huffman[i].num = i;
pq.push(huffman[i]);
}
tot = n + 1;
while (pq.size()>1)
{
hnode tmp1 = pq.top();
pq.pop();
huffman[tmp1.num].bit = 0;
hnode tmp2 = pq.top();
pq.pop();
huffman[tmp2.num].bit = 1;
int sum = tmp1.v + tmp2.v;
hnode k;
k.left = tmp1.num;
k.right = tmp2.num;
k.v = sum;
k.bit = -1;
k.num = tot++;
huffman[tot-1] = k;
pq.push(k);
}
hnode last = pq.top();
pq.pop();
string ss;
ss.clear();
getcode(last.num, ss);
for (int i = 1; i <= n; i++)
{
cout << mp[i] << " " << huffman[i].code << endl;
}
return 0;
}
数据结构之哈夫曼树
最新推荐文章于 2020-03-30 10:16:05 发布