# Huffman Coding

Huffman Coding

A：3
B：1
C：2
D：1

``````2
2 1 1
4 3 1 2 1
``````

``````1.000
2.250
``````

``````#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <iomanip>
using namespace std;
struct node
{
int x,y;
friend bool operator<(node a,node b)
{
if(a.x!=b.x)
return a.x>b.x;
return a.y>b.y;
}
};
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m,sum=0;
node u,v;
cin>>n;
m=n;
priority_queue<node> q;
while(m--)
{
cin>>u.x;
u.y=1;
q.push(u);
}
while(q.size()!=1)
{
u=q.top();
q.pop();
v=q.top();
q.pop();
int k=u.y+v.y;
u.x=u.x+v.x;
u.y=k;
sum+=k;
q.push(u);
}
cout<<setiosflags(ios::fixed)<<setprecision(3);
cout<<double(sum)/double(n)<<endl;
}
return 0;
}
``````

``````#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <iomanip>
using namespace std;
struct node
{
int x,y;
friend bool operator<(node a,node b)
{
if(a.x!=b.x)
return a.x>b.x;
return a.y>b.y;
}
};
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m,sum=0;
node u,v;
cin>>n;
m=n;
priority_queue<node> q;
while(m--)
{
cin>>u.x;
u.y=1;
q.push(u);
}
while(q.size()!=1)
{
u=q.top();
q.pop();
v=q.top();
q.pop();
int k=u.y+v.y;
u.x=u.x+v.x;
u.y=k;
sum+=k;
q.push(u);
}
cout<<setiosflags(ios::fixed)<<setprecision(3);
cout<<double(sum)/double(n)<<endl;
}
return 0;
}
``````