Pagini recente » Cod sursa (job #2693167) | Monitorul de evaluare | Istoria paginii runda/summer-challenge-2021/clasament | Cod sursa (job #544062) | Cod sursa (job #1556492)
#include <fstream>
#include <iostream>
#include <queue>
using namespace std;
#define NMax 1000005
ifstream f("huffman.in");
ofstream g("huffman.out");
struct arbore
{
long long val;
arbore *left, *right;
int dest;
arbore(long long x, int d)
{
val = x;
left = right = NULL;
dest = d;
}
arbore() {}
};
queue<arbore*> cd1, cd2;
arbore* extract_min()
{
if(cd1.empty())
{
arbore *y = cd2.front();
cd2.pop();
return y;
}
if(cd2.empty())
{
arbore *x = cd1.front();
cd1.pop();
return x;
}
arbore *x = cd1.front(), *y = cd2.front();
if(x->val < y->val)
{
cd1.pop();
return x;
}
else
{
cd2.pop();
return y;
}
}
int n;
long long sum;
pair<int,long long> sol[NMax];
void DFS(arbore* nod, long long mask, int depth)
{
if(nod->left == NULL && nod->right == NULL)
{
sol[nod->dest] = make_pair(depth, mask);
}
else
{
sum += nod->val;
DFS(nod->left, (mask<<1), depth+1);
DFS(nod->right, (mask<<1)|1, depth+1);
}
}
int main()
{
int i,x;
f>>n;
for(i=1;i<=n;++i)
{
f>>x;
cd1.push(new arbore(x, i));
}
arbore* aux;
while(cd1.size() + cd2.size() > 1)
{
aux = new arbore();
aux->left = extract_min();
aux->right = extract_min();
aux->val = aux->left->val + aux->right->val;
cd2.push(aux);
}
arbore *root = cd2.front();
DFS(root, 0, 0);
g<<sum<<"\n";
for(i=1;i<=n;++i)
{
g<<sol[i].first<<" "<<sol[i].second<<"\n";
}
f.close();
g.close();
return 0;
}