Pagini recente » Cod sursa (job #1597616) | Cod sursa (job #632744) | Cod sursa (job #721221) | Cod sursa (job #967130) | Cod sursa (job #1290654)
#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;
#define dbg(x) (cout<<#x<<" = "<<(x)<<'\n')
#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 // HOME
typedef long long int lld;
typedef pair<int, int> PII;
typedef pair<int, lld> PIL;
typedef pair<lld, int> PLI;
typedef pair<lld, lld> PLL;
const int INF = (1LL << 30) - 1;
const lld LINF = (1LL << 60) - 1;
const int dx[] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[] = {0, 1, 0, -1, 1, -1, -1, 1};
const int MOD = 666013;
const int NMAX = 1000000 + 5;
const int MMAX = 100000 + 5;
const int KMAX = 100000 + 5;
const int PMAX = 100000 + 5;
const int LMAX = 100000 + 5;
const int VMAX = 100000 + 5;
int N, cnt;
lld sol;
int V[NMAX];
lld L[NMAX];
lld C[NMAX];
deque<PII> A, B;
PII F[2 * NMAX];
PII get() {
int x, y;
PII p;
if(!A.empty())
x = A.front().first;
else
x = INF;
if(!B.empty())
y = B.front().first;
else
y = INF;
if(x < y) {
p = A.front();
A.pop_front();
} else {
p = B.front();
B.pop_front();
}
return p;
}
void dfs(int x, int cod, int len) {
if(x <= N) {
if(len == 0)
len++;
C[x] = cod;
L[x] = len;
sol += V[x] * len;
return;
}
dfs(F[x].first, cod * 2, len + 1);
dfs(F[x].second, cod * 2 + 1, len + 1);
}
int main() {
int i;
PII x, y;
#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));
}
cnt = N;
for(i = 1; i <= N - 1; i++) {
x = get();
y = get();
cnt++;
B.push_back(make_pair(x.first + y.first, cnt));
F[cnt] = make_pair(x.second, y.second);
}
dfs(cnt, 0, 0);
printf("%lld\n", sol);
for(i = 1; i <= N; i++)
printf("%lld %lld\n", L[i], C[i]);
return 0;
}