1002: 哈夫曼樹
Time Limit: 1 Sec Memory Limit: 65535 MB 64bit IO Format: %lldSubmitted: 13 Accepted: 6
[Submit][Status][Web Board]
Description
Input
Output
Sample Input
5
11 4 2 5 7
6
2 3 4 7 8 9
Sample Output
11
011
010
00
10
64
1110
1111
110
00
01
10
80
#include <bits/stdc++.h>
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
struct Node
{
int a,cnt,le,ri;
}f[4009];
string ans[4009];
int wpl;
int n;
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > >pq;
void dfs(int x,int num,string ss)
{
if(f[x].le!=-1)
{
dfs(f[x].le,num+1,ss+'0');
}
if(f[x].ri!=-1)
{
dfs(f[x].ri,num+1,ss+'1');
}
if(x<n)
{
ans[x]=ss;
wpl+=f[x].a*num;
}
}
int main()
{
while(~scanf("%d",&n))
{
int cnt=0;
while(!pq.empty())pq.pop();
int a;
for(cnt=0;cnt<n;cnt++)
{
scanf("%d",&a);
pq.push(make_pair(a,cnt));
f[cnt].a=a;
f[cnt].cnt=cnt;
f[cnt].le=-1;f[cnt].ri=-1;
}
while(pq.size()>1)
{
pair<int,int>le=pq.top();
pq.pop();
pair<int,int>ri=pq.top();
pq.pop();
int fa=le.first+ri.first;
pq.push(make_pair(fa,cnt));
f[cnt].a=fa;
f[cnt].cnt=cnt;
f[cnt].le=le.second;
f[cnt].ri=ri.second;
cnt++;
}
int root=pq.top().second;
wpl=0;
dfs(root,0,"");
for(int i=0;i<n;i++)
cout<<ans[i]<<endl;
printf("%d\n",wpl);
}
return 0;
}