Cod sursa(job #2901450)

Utilizator disinfoion ion disinfo Data 13 mai 2022 19:13:50
Problema Coduri Huffman Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#define MAX 1000010
using namespace std;

int f[2*MAX];
int tree[2*MAX];
int leftc[2*MAX];
int rightc[2*MAX];
int d[MAX];
long long c[MAX];
long long sum = 0;

class Compare
{
public:
    bool operator() (int a, int b)
    {
        return f[a] > f[b];
    }
};

priority_queue<int, vector<int>, Compare> pq;

void compute_code(int node, int depth, long long code){
	if(!leftc[node]){
		d[node] = depth;
		c[node] = code;
		sum += depth * f[node];
	}
	else{
		compute_code(leftc[node], depth + 1, 2*code);
		compute_code(rightc[node], depth + 1, 2*code + 1);
	}

}

int main(){
	ifstream fin;
	ofstream fout;
	fin.open("huffman.in");
	fout.open("huffman.out"); 
	int m, n, q, a, b, i, j;

	fin >> n;
	for(int i=1; i <= n; ++i){
		fin >> f[i];
		tree[i] = 0;
		pq.push(i);
	}

	int new_node;
	new_node = n;

	while(pq.size() > 1){
		i = pq.top();
		pq.pop();
		j = pq.top();
		pq.pop();

		++new_node;
		tree[i] = tree[j] = new_node;
		f[new_node] = f[i] + f[j];
		leftc[new_node] = i;
		rightc[new_node] = j;
		pq.push(new_node);

	}
	int root = pq.top();
	compute_code(root, 0, 0);
	fout << sum << "\n";
	for(int i = 1; i<=n; ++i){
		fout << d[i] << " " << c[i] << "\n";
	}

}