Cod sursa(job #1410570)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 31 martie 2015 09:56:43
Problema Coduri Huffman Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#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;
}