Cod sursa(job #1759065)

Utilizator CodrutLemeniCodrut Lemeni CodrutLemeni Data 18 septembrie 2016 14:32:13
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
#define N 1000000

using namespace std;


struct node{
    long long val;
    int ord;
    struct node *left=NULL ,*right=NULL;
};

class cmp{
public:

    bool operator()(node x,node y){
        return x.val>y.val;
    }
};

priority_queue < struct node, vector<struct node>,cmp  > que;
long long s;
long long v[N];
int l[N];

void gen( node *x , long long vcod, int lvl ){

    if(x->ord==0){
        s+=x->val;
    }
    v[ x->ord ]=vcod;
    l[ x->ord ]=lvl;
    if(x->left==NULL && x->right==NULL){
        return;
    }else{
        if(x->left!=NULL){
            gen(x->left,2*vcod,lvl+1);
        }
        if(x->right!=NULL){
            gen(x->right,2*vcod+1,lvl+1);

        }
    }

}

int main(){
    int i,n,frec;

    freopen("huffman.in","r",stdin);
    freopen("huffman.out","w",stdout);

    scanf("%d",&n);

    for(i=1;i<=n;i++){
        scanf("%d",&frec);

        struct node a;
        a.val=frec;
        a.ord=i;

        que.push(a);
    }

    while(que.size()>1){
        node *x= new node;
        *x=que.top();
        que.pop();

        node *y= new node;
        *y=que.top();
        que.pop();

        node z;
        z.val=x->val+y->val;
        z.ord=0;
        z.left=x;
        z.right=y;

        que.push(z);

    }

    struct node temp;
    temp=que.top();

    gen( &temp , 0 , 0  );

    printf("%lld\n",s);

    for(i=1;i<=n;i++){
        printf("%d %lld\n",l[i],v[i]);
    }

    return 0;
}