Cod sursa(job #2500243)

Utilizator robx12lnLinca Robert robx12ln Data 27 noiembrie 2019 16:04:16
Problema Coduri Huffman Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include<bits/stdc++.h>
using namespace std;

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

const int INF = 0x3f3f3f3f;
const int DIM = 1e6 + 5;
int arr[DIM * 2 + 5];

int N, pos, p, last;
long long sol;
pair<int,long long> ans[DIM];
vector< pair<int,bool> > edge[DIM * 2 + 5];

void dfs( int nod, int lg, long long cod ){

    if( 1 <= nod && nod <= N ){
        sol += arr[nod] * lg;
        ans[nod].first = lg;
        ans[nod].second = cod;
        return;
    }

    for( int i = 0; i < edge[nod].size(); i++ ){
        dfs( edge[nod][i].first, lg + 1, (cod<<1) + edge[nod][i].second );
    }
    return;
}

int main(){

    fin >> N;
    for( int i = 1; i <= N; i++ )
        fin >> arr[i];
    pos = N + 1;
    last = N;
    p = 1;

    for( int step = 1; step < N; step++ ){

        int s1 = INF, s2 = INF, s3 = INF;
        if( p < N )
            s1 = arr[p] +  arr[p + 1];
        if( pos <= last && p <= N )
            s2 = arr[p] + arr[pos];
        if( pos + 1 <= last )
            s3 = arr[pos] + arr[pos + 1];

        if( s1 <= s2 && s1 <= s3 ){
            last++;
            edge[last].push_back( {p, 0} );
            edge[last].push_back( {p + 1, 1} );
            arr[last] = s1;
            p += 2;
            continue;
        }

        if( s2 <= s3 && s2 <= s1 ){
            last++;
            if( arr[p] < arr[pos] )
                edge[last].push_back( {p, 0} ), edge[last].push_back( {pos, 1} );
            else
                edge[last].push_back( {pos, 0} ), edge[last].push_back( {p, 1} );
            arr[last] = s2;
            pos++;
            p++;
            continue;
        }

        if( s3 <= s1 && s3 <= s2 ){
            last++;
            edge[last].push_back( {pos, 0} );
            edge[last].push_back( {pos + 1, 1} );
            arr[last] = s3;
            pos += 2;
            continue;
        }

    }

    dfs( last, 0, 0 );
    fout << sol << "\n";
    for( int i = 1; i <= N; i++ )
        fout << ans[i].first << " " << ans[i].second << "\n";
    return 0;
}