Pagini recente » Cod sursa (job #2906294) | Cod sursa (job #569641) | Cod sursa (job #77240) | Cod sursa (job #271896) | Cod sursa (job #1410570)
#include<algorithm>
#include<bitset>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<deque>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<vector>
using namespace std;
#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "huffman";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif
typedef long long int lld;
typedef pair<int, int> PII;
typedef pair<lld, int> PLI;
typedef pair<int, lld> PIL;
const int NMAX = 1000000 + 5;
const lld INF = (1LL << 62);
int N;
int V[NMAX];
deque<PLI> A, B;
PII sons[2 * NMAX];
lld L;
PIL C[NMAX];
PII get() {
PLI a, b;
if(!A.empty()) a = A.front();
else a = make_pair(INF, 0);
if(!B.empty()) b = B.front();
else b = make_pair(INF, 0);
if(a < b) {
A.pop_front();
return a;
} else {
B.pop_front();
return b;
}
}
void dfs(int x, int len, lld cod) {
if(!x)
return;
if(x <= N) {
L += len * V[x];
C[x] = make_pair(len, cod);
return;
}
dfs(sons[x].first, len + 1, 2 * cod + 0);
dfs(sons[x].second, len + 1, 2 * cod + 1);
}
int main() {
int i, x;
PLI a, b;
#ifndef ONLINE_JUDGE
freopen(inputFile.c_str(), "r", stdin);
freopen(outputFile.c_str(), "w", stdout);
#endif
scanf("%d", &N);
for(i = 1; i <= N; i++) {
scanf("%d", &V[i]);
A.push_back(make_pair(V[i], i));
}
for(i = 1; i <= N; i++) {
a = get();
b = get();
B.push_back(make_pair(a.first + b.first, N + i));
sons[N + i] = make_pair(a.second, b.second);
}
dfs(2 * N, -1, 0);
printf("%lld\n", L);
for(i = 1; i <= N; i++)
printf("%d %lld\n", C[i].first, C[i].second);
return 0;
}