Cod sursa(job #1887298)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 21 februarie 2017 15:10:59
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <fstream>

using namespace std;

ifstream fin ("huffman.in"); ofstream fout ("huffman.out");

typedef long long i64;

const int nmax = 1e6;
const i64 inf = (1LL << 60);

int n;
int h[nmax + 1];
i64 v[nmax + 1];
int g[2 * nmax + 1][ 2 ];

int f1, l1, f2, l2;
pair<i64, int> q1[nmax + 1], q2[nmax + 1];

void dfs (int nod, i64 nr, int _h) {
    int val = -1;
    for (int i = 0; i < 2; ++ i) {
        if (g[ nod ][ i ] != 0) {
            ++ val;
            dfs(g[ nod ][ i ], nr * 2 + val, _h + 1);
        }
    }

    if (val == -1) {
        v[ nod ] = nr;
        h[ nod ] = _h;
    }
}

int main() {
    fin >> n;

    f1 = f2 = 0; l1 = l2 = -1;
    for (int i = 1; i <= n; ++ i) {
        i64 x;
        fin >> x;
        q1[ ++ l1 ] = make_pair(x, i);
    }

    i64 ans = 0;
    int nr = n;
    while (l1 - f1 + 1 + l2 - f2 + 1 > 1) {
        i64 sum = inf;

        if (f1 <= l1 && f2 <= l2 && q1[ f1 ].first + q2[ f2 ].first <= sum) {
            sum = q1[ f1 ].first + q2[ f2 ].first;
        }
        if (f1 + 1 <= l1 && q1[ f1 ].first + q1[f1 + 1].first <= sum) {
            sum = q1[ f1 ].first + q1[f1 + 1].first;
        }
        if (f2 + 1 <= l2 && q2[ f2 ].first + q2[f2 + 1].first <= sum) {
            sum = q2[ f2 ].first + q2[f2 + 1].first;
        }

        ++ nr;
        if (f1 <= l1 && f2 <= l2 && q1[ f1 ].first + q2[ f2 ].first == sum) {
            g[ nr ][ 0 ] = q1[f1 ++].second;
            g[ nr ][ 1 ] = q2[f2 ++].second;
        } else if (f1 + 1 <= l1 && q1[ f1 ].first + q1[f1 + 1].first == sum) {
            g[ nr ][ 0 ] = q1[f1 ++].second;
            g[ nr ][ 1 ] = q1[f1 ++].second;
        } else if (f2 + 1 <= l2 && q2[ f2 ].first + q2[f2 + 1].first == sum) {
            g[ nr ][ 0 ] = q2[f2 ++].second;
            g[ nr ][ 1 ] = q2[f2 ++].second;
        }

        ans += sum;
        q2[ ++ l2 ] = make_pair(sum, nr);
    }

    fout << ans << "\n";

    dfs(nr, 0, 0);

    for (int i = 1; i <= n; ++ i) {
        fout << h[ i ] << " " << v[ i ] << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}