Cod sursa(job #1991060)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 14 iunie 2017 20:11:23
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <list>

struct Node {
    Node() : symbol(-1), freq(0), left(-1), right(-1) {}
    int symbol;
    int left, right;

    long long freq;
    long long len;
    long long code;
};

int pop(std::list<int> &lA, std::list<int> &lB, std::vector<Node> &myV) {
    int res;
    if (lA.empty() && lB.empty()) {
        return -1;
    } else if (lA.empty()) {
        res = lB.front();
        lB.pop_front();
    } else if (lB.empty()) {
        res = lA.front();
        lA.pop_front();
    } else if (myV[lA.front()].freq > myV[lB.front()].freq) {
        res = lB.front();
        lB.pop_front();
    } else {
        res = lA.front();
        lA.pop_front();
    }
    return res;
}

void dfs(int node, long long len, long long code, long long &sum, std::vector<Node> &myV) {
    if (myV[node].symbol != -1) {
        myV[node].len = len;
        myV[node].code = code;
        return;
    }
    sum += myV[node].freq;
    if (myV[node].left != -1) {
        dfs(myV[node].left, len + 1, code << 1, sum, myV);
    }
    if (myV[node].right != -1) {
        dfs(myV[node].right, len + 1, (code << 1) + 1, sum, myV);
    }
}

int main() {
    std::ifstream fileIn("huffman.in");
    std::ofstream fileOut("huffman.out");

    int nV;

    fileIn >> nV;

    std::list<int> lA, lB;
    std::vector<Node> myV;

    Node aux;
    for (int i(0); i < nV; i++) {
        aux = Node();
        aux.symbol = i;
        fileIn >> aux.freq;
        myV.push_back(aux);
        lA.push_back(i);
    }

    int l, r;
    for (;;) {
        l = pop(lA, lB, myV);
        r = pop(lA, lB, myV);
        if (r == -1) {
            break;
        }
        lB.push_back(myV.size());
        aux = Node();
        aux.left = l;
        aux.right = r;
        aux.freq += myV[l].freq + myV[r].freq;
        myV.push_back(aux);
    }

    long long sum(0);

    dfs(l, 0, 0, sum, myV);

    fileOut << sum << '\n';

    for (int i(0); i < nV; i++) {
        fileOut << myV[i].len << ' ' << myV[i].code << '\n';
    }

    fileIn.close();
    fileOut.close();
    return 0;
}