Description
有n(n<=26)个带权结点,从a开始的n个字母分别表示这n个结点,他们分别代n个权值,试以它们为叶子结点构造一棵哈夫曼树(请按照左子树根节点的权小于等于右子树根节点的权的次序构造,若两结点相等时,按照字典顺序分别为左子树和右子树)。 最后求出该哈夫曼树的带权路径长度.
Input
第一行为一个n的值;第二行为n个字母,中间用空格分开;第三行为n个数字,分别表示着n个字母代表的数值.
Output
共计n+1行,前n行分别为按照字母表的顺序输出各个字母和编码,中间用冒号分开,第n+1行为该哈夫曼树的带权路径长度
Sample Input
7
a b c d e f g
3 7 8 2 5 8 4
Sample Output
a:1101
b:111
c:00
d:1100
e:101
f:01
g:100
100
思路
显然的哈夫曼树,注意输出的WPL是乘积和。
code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
struct f{
int v,l,r;
char o;
string s;
} a[1000001];
int tot;
int x[10001];
int n;
string s;
void dfs(int x,int dep)
{
if (a[x].l==0&&a[x].r==0)
{
a[x].s=s.substr(0,dep+1);
tot+=dep*a[x].v;
return;
}
if (a[x].l!=0)
{
s+='0';
dfs(a[x].l,dep+1);
s.erase(s.size()-1,1);
}
if (a[x].r!=0)
{
s+='1';
dfs(a[x].r,dep+1);
s.erase(s.size()-1,1);
}
return;
}
bool cmp(int c,int b)
{
if (a[c].v==a[b].v) return a[c].o>a[b].o;
return a[c].v>a[b].v;
}
int main()
{
cin>>n;
for (int i=1;i<=n;i++) cin>>a[i].o;
for (int i=1;i<=n;i++)
{
cin>>a[i].v;
x[i]=i;
}
sort(x+1,x+1+n,cmp);
for (int i=n;i>1;i--)
{
int xx=n+n-i+1;
a[xx].v=a[x[i]].v+a[x[i-1]].v;
a[xx].l=x[i];
a[xx].r=x[i-1];
int j;
for (j=i-1;j>0&&a[xx].v>=a[x[j]].v;j--) x[j+1]=x[j];
x[j+1]=xx;
}
dfs(n+n-1,0);
for (int i=1;i<=n;i++) cout<<a[i].o<<':'<<a[i].s<<endl;
cout<<tot;
return 0;
}