Cod sursa(job #1999083)

Utilizator B_RazvanBaboiu Razvan B_Razvan Data 10 iulie 2017 10:41:23
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <cstdio>
#include <queue>
#define NMAX 1000005

using namespace std;

int n, nrTati=1, sol;
pair <int, int> tati[NMAX];
queue <pair <long, int> >q1, q2;


void read()
{
    scanf("%d", &n);
    int x;
    for(int i=1; i<=n; ++i)
    {
        scanf("%d", &x);
        q1.push(make_pair(x, i));
    }
}

int minim()
{
    int x;
    if(!q1.empty() && q1.front().first <= q2.front().first)
    {
        x=q1.front().first;
        q1.pop();
    }
    else if(!q2.empty())
    {
        x=q2.front().first;
        q2.pop();
    }
    return x;
}

void codare()
{
    int x1, x2;
    while(q1.size() + q2.size() > 1)
    {
        x1 = minim();
        if(q1.size() + q2.size() >= 1)
            x2 = minim();
        q2.push(make_pair(x1 + x2, ++n));
        sol += x1+x2;
        x1 = 0;
        x2 = 0;

        tati[nrTati].first = n;
        tati[nrTati].second = 0;
        nrTati++;
        tati[nrTati].first = n;
        tati[nrTati].second = 1;
        nrTati++;
    }

    if(!q1.empty())
    {
        sol+=q1.front().first;
    }
}

int main()
{
    freopen("huffman.in", "r", stdin);
    freopen("huffman.out", "w", stdout);
    read();
    codare();
    printf("%d", sol);
    return 0;
}