Pagini recente » Cod sursa (job #806442) | Cod sursa (job #1505378) | Cod sursa (job #1070095) | Cod sursa (job #1949628) | Cod sursa (job #1662001)
#include<fstream>
#include<queue>
using namespace std;
ifstream in("huffman.in");
ofstream out("huffman.out");
int N;
struct Node
{
int f1, f2;
long long val;
};
Node arb[3000010];
vector<pair<int, long long>> r;
vector<pair<int, long long>>::iterator it;
int t = 0;
long long sol=0;
struct comparator
{
bool operator() (const int n1, const int n2)
{
return arb[n1].val > arb[n2].val;
}
};
priority_queue<int,vector<int>,comparator> pq;
void DFS(int i,long long nr,long long e)
{
if (arb[i].f1 != 0)
{
DFS(arb[i].f1,nr+1,e<<1);
DFS(arb[i].f2,nr+1,(e<<1)|1LL);
}
else
{
r.push_back(make_pair(nr, e));
sol += nr*arb[i].val;
}
}
int main()
{
in >> N;
for (int i = 1;i <= N;++i)
{
int e;
in >> e;
arb[++t].f1 = 0, arb[t].f2 = 0,arb[t].val=e;
pq.push(t);
}
while (pq.size() != 1)
{
int e1, e2;
e1 = pq.top();
pq.pop();
e2 = pq.top();
pq.pop();
arb[++t].f1 = e1;
arb[t].f2 = e2;
arb[t].val = arb[e1].val + arb[e2].val;
pq.push(t);
}
DFS(pq.top(), 0, 0);
out << sol<<'\n';
for (it = r.begin();it != r.end();++it)
out << (*it).first << " " << (*it).second << '\n';
return 0;
}