Cod sursa(job #628451)

Utilizator sunt_emoSunt emo sunt_emo Data 1 noiembrie 2011 14:14:06
Problema Coduri Huffman Scor 65
Compilator c Status done
Runda Arhiva educationala Marime 1.57 kb
#include <stdio.h>
#include <stdlib.h>
#define Inf 2000000000

typedef struct Node {
    int data,ind;
    struct Node *left,*right;
} Node;

short p[1000010];
int q[1000010];
long long lg=0;

inline void print (Node * k,int u,int v)
{
    if (k->ind) {
        p[k->ind]=u;
        q[k->ind]=v;
        lg+=u*k->data;
        return;
    }
    print (k->left,u+1,v<<1);
    print (k->right,u+1,(v<<1)+1);
}

int main () {
    FILE * in=fopen ("huffman.in","r");
    FILE * out=fopen ("huffman.out","w");
    int i,n,c1=0,c2=0,d2=0;
    fscanf (in,"%d",&n);
    Node * t,*t1,*t2,*inf;
    Node ** k1=(Node**) malloc ((n+10)*sizeof (Node*));
    Node ** k2=(Node**) malloc (((n<<1)+10)*sizeof (Node*));
    for (i=1; i<=n; i++) {
        t=(Node*) malloc (sizeof (Node));
        fscanf (in,"%lld",&t->data);
        t->ind=i;
        t->left=0;
        t->right=0;
        k1[i-1]=t;
    }
    k1[n]=malloc (sizeof (Node*));
    k1[n]->data=Inf;
    inf=malloc (sizeof (Node*));
    inf->data=Inf;
    k2[0]=inf;
    while (1) {
        t1=(k1[c1]->data<=k2[c2]->data ? k1[c1++] : k2[c2++]);
        t2=(k1[c1]->data<=k2[c2]->data ? k1[c1++] : k2[c2++]);
        if (t2->data==Inf) break;
        t=(Node*) malloc (sizeof (Node));
        t->data=t1->data+t2->data;
        t->ind=0;
        t->left=t1;
        t->right=t2;
        k2[d2++]=t;
        k2[d2]=inf;
    }
    print (k2[c2-1],0,0);
    fprintf (out,"%lld\n",lg);
    for (i=1; i<=n; i++) fprintf (out,"%d %d\n",p[i],q[i]);
    fclose (in);
    fclose (out);
    return 0;
}