登录后台

页面导航

本文编写于 1252 天前,最后修改于 1252 天前,其中某些信息可能已经过时。
#include <bits/stdc++.h>
using namespace std;
struct node
{
    int lchild, rchild;
};
node child[100500] = {0};
struct node1
{
    int val, key;
    bool operator<(const node1 &a) const
    {
        return a.val < val;
    }
};
priority_queue<node1> que;
int a[100500] = {0};
string str[100500];
int cnt = 0;
int ans=0;
int dfs(int k, string tem)
{
    if (child[k].lchild == -1 && child[k].rchild == -1)
    {
        cout << str[k] << ' ' << tem << endl;
        ans+=(int)tem.size()*a[k];
        return 0;
    }
    dfs(child[k].lchild, tem + "0");
    dfs(child[k].rchild, tem + "1");
    return 0;
}
int main()
{
    int n;
    node1 tem1, tem2;
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    for (int i = 1; i <= n; i++)
        cin >> str[i];
    for (int i = 1; i <= n; i++)
    {
        que.push({a[i], ++cnt});
        child[cnt].lchild = child[cnt].rchild = -1;
    }
    while (que.size() > 1)
    {
        tem1 = que.top();
        que.pop();
        tem2 = que.top();
        que.pop();
        cnt += 1;
        child[cnt].lchild = tem1.key;
        child[cnt].rchild = tem2.key;
        que.push({tem1.val + tem2.val, cnt});
    }
    dfs(cnt, "");
    cout<<ans<<endl;
}

输入:

6
50 60 150 200 240 300
a b c d e f

输出:

d 00
e 01
a 1000
b 1001
c 101
f 11
2370

注:输出一共n+1行,其中前n行为字母对应的哈夫曼编码,n+1行为所需二进制长度。