Cod sursa(job #1777728)

Utilizator CodrutLemeniCodrut Lemeni CodrutLemeni Data 12 octombrie 2016 20:38:51
Problema Coduri Huffman Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>

#include <queue>

#define N 1000000

using namespace std;

struct nod {
  long long  val;
  int ord;

  struct nod *left, *right;
};

queue <struct nod*> qfr, qin;
long long  v[N], s;
int l[N];

void gen(nod *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) {
      gen(x->left, 2*vcod, lvl+1);
    }
    if (x->right != NULL) {
      gen(x->right, 2*vcod+1, lvl+1);
    }
}

int main() {
    struct nod *nodx;
    int i, x, n;
    bool spy = 0;

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

    scanf("%d",&n);

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

	nodx = new nod;
        nodx->val = x;
        nodx->ord = i;
	nodx->left = NULL; nodx->right = NULL;

        qfr.push(nodx);
    }

    while (!(qfr.size() == 0 && qin.size() == 1)) {
        nod *a = NULL, *b = NULL;

        for(i = 0; i < 2; i++) {
            if (qfr.empty() && qin.empty()) {
              spy = 1;
              break;
            }

            if (qfr.empty()) {
              b = a;
              a = qin.front(); qin.pop();
            } else if (qin.empty()) {
              b = a;
              a = qfr.front(); qfr.pop();
            } else {
                if (qfr.front()->val > qin.front()->val) {
                  b = a;
                  a = qin.front(); qin.pop();
                } else {
                  b = a;
                  a = qfr.front(); qfr.pop();
                }
            }
        }

        if (spy == 1) {
          qin.push(a);
          break;
        }

        nod *c = new nod;
        c->val = a->val + b->val;
        c->ord = 0;
        c->left = b; c->right = a;
        qin.push(c);
    }

    nodx = qin.front();

    gen(nodx, 0, 0);

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

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

    return 0;
}