Cod sursa(job #1214652)

Utilizator CostanMiriamCostan Miriam CostanMiriam Data 31 iulie 2014 00:45:41
Problema Coduri Huffman Scor 85
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>

using namespace std;

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

int n,i,k,p1,p2;
long long sum;
struct data {
    long long x;
    int y;
    int z;
}v[(1000001)<<1];
struct data1 {
    int x;
    int y;
}r[1000010];
bool verif1 () {
    if (p1>=n)
        return 0;
    if (v[p1].x+v[p1+1].x>v[p1].x+v[p2].x && p2<=k)
        return 0;
    if (v[p1].x+v[p1+1].x>v[p2].x+v[p2+1].x && p2<k)
        return 0;
    return 1;
}
bool verif2() {
    if (p1>n||p2>k)
        return 0;
    if (v[p1].x+v[p2].x>v[p1].x+v[p1+1].x && p1<n)
        return 0;
    if (v[p1].x+v[p2].x>v[p2].x+v[p2+1].x && p2<k)
        return 0;
    return 1;
}
void dfs (int nod, int niv, int b) {
    if (v[nod].y!=0) {
        dfs (v[nod].y,niv+1,b*2+1);
        dfs (v[nod].z,niv+1,b*2);
    }else {
        r[nod].x=niv;
        r[nod].y=b;
    }
}

int main () {

    fin>>n;
    for(i=1;i<=n;i++){
        k++;
        fin>>v[k].x;
    }
    v[++k].x=v[1].x+v[2].x;
    v[k].y=1;
    v[k].z=2;
    sum+=v[k].x;
    p1=3;
    p2=k;
    while (p2<k||p1<=n) {
        if (verif1()) {
            v[++k].x=v[p1].x+v[p1+1].x;
            v[k].y=p1;
            v[k].z=p1+1;
            p1+=2;
            sum+=v[k].x;
        }else
            if (verif2()) {
                v[++k].x=v[p1].x+v[p2].x;
                v[k].y=p2;
                v[k].z=p1;
                p1++;
                p2++;
                sum+=v[k].x;
            }else {
                v[++k].x=v[p2].x+v[p2+1].x;
                v[k].y=p2;
                v[k].z=p2+1;
                p2+=2;
                sum+=v[k].x;
            }
    }

    fout<<sum<<"\n";

    dfs (k,0,0);

    for (i=1;i<=n;i++)
        fout<<r[i].x<<" "<<r[i].y<<"\n";

    return 0;
}