Pagini recente » Cod sursa (job #2063289) | Cod sursa (job #2315143) | Cod sursa (job #2243860) | Cod sursa (job #419815) | Cod sursa (job #1501146)
#include <algorithm>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
#define MAX_N 1000010
#define pb push_back
using namespace std;
int n;
vector <long long> weightQueue;
vector <pair <long long, long long> > parents;
long long sol[2 * MAX_N];
int level[2 * MAX_N];
int takeMin(int initQ, int newQ) {
if (initQ >= n)
return newQ;
if (newQ >= weightQueue.size())
return initQ;
if (weightQueue[initQ] < weightQueue[newQ])
return initQ;
return newQ;
}
int main() {
ifstream cin("huffman.in");
freopen("huffman.out", "w", stdout);
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
weightQueue.pb(x);
parents.pb(make_pair(0, 0));
}
int firstEl = 0;
int firstQ = n;
for (int iter = n - 1; iter; iter--) {
int p1 = takeMin(firstEl, firstQ);
if (p1 == firstEl)
firstEl++;
else firstQ++;
int p2 = takeMin(firstEl, firstQ);
if (p2 == firstEl)
firstEl++;
else firstQ++;
weightQueue.pb(weightQueue[p1] + weightQueue[p2]);
parents.pb(make_pair(p1, p2));
}
for (int i = weightQueue.size() - 1; i >= n; i--) {
sol[parents[i].first] = sol[i] * 2 + 1;
sol[parents[i].second] = sol[i] * 2;
level[parents[i].first] = level[parents[i].second] = level[i] + 1;
}
long long minSol = 0;
for (int i = 0; i < n; i++)
minSol += weightQueue[i] * level[i];
printf("%lld\n", minSol);
for (int i = 0; i < n; i++)
printf("%d %lld\n", level[i], sol[i]);
return 0;
}