Cod sursa(job #2796697)

Utilizator mjmilan11Mujdar Milan mjmilan11 Data 8 noiembrie 2021 17:36:00
Problema Coduri Huffman Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
const ll NMAX = 2000005;
pair<int, pair<int,ll> > rasp[NMAX];
ll a[NMAX];
int st[NMAX],dr[NMAX];
ll n,nr,k,sum=0,dim;
queue <int> q1,q2;
void citire(){
    fin >> n;
    for(ll i=1;i<=n;i++){
        fin >> nr;
        q1.push(i);
        a[++k]=nr;
    }
}
void add_(ll x,ll y){
    a[++k]=a[x]+a[y];
    sum+=a[k];
    st[k]=x;
    dr[k]=y;
    q2.push(k);
}
ll minim(){
    if(q1.empty()){
        ll x=q2.front();
        q2.pop();
        return x;
    }
    if(q2.empty()){
        ll x=q1.front();
        q1.pop();
        return x;
    }
    if(a[q1.front()]<a[q2.front()]){
        ll x=q1.front();
        q1.pop();
        return x;
    } else {
        ll x=q2.front();
        q2.pop();
        return x;
    }
}
void dfs(ll poz,ll val,ll cnt){
    if(st[poz]==0 and dr[poz]==0){
        rasp[++dim].first=poz;
        rasp[dim].second.first=cnt;
        rasp[dim].second.second=val;
    } else {
        dfs(st[poz],2*val,cnt+1);
        dfs(dr[poz],2*val+1,cnt+1);
    }
}
void solve(){
    while(q1.size()+q2.size()>1){
        ll x=minim();
        ll y=minim();
        add_(x,y);
    }
    fout << sum << '\n';
    dfs(k,0,0);
    sort(rasp+1,rasp+dim+1);
    for(ll i=1;i<=dim;i++){
        fout << rasp[i].second.first << ' ' << rasp[i].second.second << '\n';
    }
}
int main()
{
    citire();
    solve();
    return 0;
}