Cod sursa(job #2620532)

Utilizator radustn92Radu Stancu radustn92 Data 29 mai 2020 00:16:53
Problema Coduri Huffman Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
const int NMAX = 1000505;

int N, A[NMAX];

struct node {
	int weight, originalIdx;

	node* leftChild;
	node* rightChild;

	node(int _weight, int _originalIdx = -1, node* _leftChild = NULL, node* _rightChild = NULL) {
		originalIdx = _originalIdx;
		weight = _weight;
		leftChild = _leftChild;
		rightChild = _rightChild;
	}
};

queue<node*> leaves;
queue<node*> internalNodes;
pair<int, long long> result[NMAX];
long long totalLength;

node* extractMinimum() {
	node* result = NULL;
	if (leaves.empty() || (!internalNodes.empty() && internalNodes.front() -> weight < leaves.front() -> weight)) {
		result = internalNodes.front();
		internalNodes.pop();
	} else {
		result = leaves.front();
		leaves.pop();
	}

	return result;
}

void dfs(node* currNode, int depth, long long currPrefix) {
	if (currNode == NULL) {
		return;
	} else if (currNode -> originalIdx != -1) {
		result[currNode -> originalIdx] = {depth, currPrefix};
		totalLength += currNode -> weight * depth;
		return;
	}

	dfs(currNode -> leftChild, depth + 1, currPrefix << 1);
	dfs(currNode -> rightChild, depth + 1, (currPrefix << 1) + 1);
}

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

	cin.tie(NULL);
	ios_base::sync_with_stdio(false);

	cin >> N;
	for (int i = 1; i <= N; i++) {
		cin >> A[i];
		leaves.push(new node(A[i], i));
	}

	while (leaves.size() + internalNodes.size() > 1) {
		node* firstMin = extractMinimum();
		node* secondMin = extractMinimum();

		node* newNode = new node({firstMin -> weight + secondMin -> weight, -1, firstMin, secondMin});
		internalNodes.push(newNode);
	}

	dfs(internalNodes.front(), 0, 0);
	cout << totalLength << "\n";
	for (int i = 1; i <= N; i++) {
		cout << result[i].first << " " << result[i].second << "\n";
	}
	return 0;
}