Cod sursa(job #3236850)

Utilizator Radu_MocanasuMocanasu Radu Radu_Mocanasu Data 3 iulie 2024 08:05:00
Problema Coduri Huffman Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
int v[1000005];
int t[2000005];
bool viz[2000005];
int nrb[2000005];
long long r[2000005];
queue < pair <int, int> > q;

int main()
{
    int n,i,x;
    long long rez = 0;
    fin >> n;
    for(i = 1; i <= n; i++) fin >> v[i];
    if(n == 1){
        fout << v[1] << "\n";
        fout << "1 0";
        return 0;
    }
    int k = 1,e = n;
    t[k] = t[k + 1] = ++e;
    q.push({e, v[k] + v[k + 1]});
    k += 2;
    while(k <= n){
        if(k == n || v[k] + q.front().second <= v[k] + v[k + 1]){
            t[k] = t[q.front().first] = ++e;
            q.push({e, v[k] + q.front().second});
            q.pop();
            k++;
        }
        else{
            t[k] = t[k + 1] = ++e;
            q.push({e, v[k] + v[k + 1]});
            k += 2;
        }
    }
    while(!q.empty()){
        k = q.front().first;
        q.pop();
        if(q.empty()) break;
        int k2 = q.front().first;
        q.pop();
        t[k] = t[k2] = ++e;
        q.push({e, 0});
    }
    for(i = e - 1; i > 0; i--){
        if(!viz[t[i]]){
            r[i] = (r[t[i]] << 1LL);
            nrb[i] = nrb[t[i]] + 1;
            viz[t[i]] = 1;
        }
        else{
            r[i] = (r[t[i]] << 1LL) + 1;
            nrb[i] = nrb[t[i]] + 1;
        }
        if(i <= n) rez += 1LL * (nrb[i] * v[i]);
    }
    fout << rez << "\n";
    for(i = 1; i <= n; i++) fout << nrb[i] << " " << r[i] << "\n";
    return 0;
}