Pagini recente » Istoria paginii template/grigore-moisil-2008 | Cod sursa (job #1138183) | Cod sursa (job #2108957) | Cod sursa (job #886956) | Cod sursa (job #2910540)
#include <bits/stdc++.h>
#define LIM 1<<17
/// TONI BO$$ was here
/// #MLC
using namespace std;
char BUF[LIM];
int poz;
inline char getChar(){
poz++;
if(poz>=LIM){
fread(BUF,LIM,1,stdin);
poz=0;
}
return BUF[poz];
}
inline int getNr(){
int r=0, semn=1;
char ch=getChar();
while(isdigit(ch)==0 && ch!='-') ch=getChar();
if(ch=='-'){
semn=-1;
ch=getChar();
}
while(isdigit(ch)!=0){
r=r*10+semn*(ch-'0');
ch=getChar();
}
return r;
}
struct node
{
int val;
long long freq;
node *leftChild;
node *rightChild;
bool operator <(const node &oth) const
{
return freq > oth.freq;
}
};
struct Compare
{
bool operator ()(node *x1, node *x2){
return x1->freq > x2->freq;}
};
priority_queue <node *, vector <node *>, Compare> q;
long long code[1000001];
int level[1000001];
void dfs(node *cur, int lev, long long nr)
{
if(cur->val)
{
level[cur->val] = lev;
code[cur->val] = nr;
return ;
}
dfs(cur->leftChild, lev + 1, nr << 1);
dfs(cur->rightChild, lev + 1, (nr << 1) + 1);
}
int main()
{
int n, i, f;
freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
poz = LIM;
n = getNr();
long long sum = 0;
for(i = 1; i <= n; i++)
{
f = getNr();
node *aux = (node *) malloc(sizeof(node));
aux->val = i;
aux->freq = f;
aux->leftChild = nullptr;
aux->rightChild = nullptr;
q.push(aux);
}
while(true)
{
node *x1 = q.top();
q.pop();
if(q.empty())
{
q.push(x1);
break;
}
node *x2 = q.top();
q.pop();
node *x3 = (node *) malloc(sizeof(node));
x3->val = 0;
x3->freq = x1->freq + x2->freq;
sum += x3->freq;
x3->leftChild = x1;
x3->rightChild = x2;
q.push(x3);
}
printf("%lld\n", sum);
node *start = q.top();
dfs(start, 0, 0);
for(i = 1; i <= n; i++)
printf("%d %lld\n", level[i], code[i]);
return 0;
}