Cod sursa(job #2619390)

Utilizator minecraft3Vintila Valentin Ioan minecraft3 Data 27 mai 2020 16:23:46
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>
#define N 1000005

using namespace std;

long long v[2*N];
int n, on, st[2*N], dr[2*N];
queue<int> q[2];
pair<int, long long> rez[N];

void add_node(int a, int b) {
	v[++n] = v[a] + v[b];
	st[n] = a;
	dr[n] = b;
	q[1].push(n);
}

void dfs(int x, long long cv, int cvs) {
	if(st[x]) {
		dfs(st[x], (cv << 1LL), cvs+1);
		dfs(dr[x], (cv << 1LL) + 1LL, cvs+1);
	} else if(x <= on) rez[x] = {cvs, cv};
}

int main() {
	ifstream fin("huffman.in");
	ofstream fout("huffman.out");

	fin >> n; on = n;
	for(int i = 1; i <= n; ++i) {
		fin >> v[i]; q[0].push(i);
	}

	while(q[0].size() + q[1].size() > 1) {
		int a, b;

		if(q[0].empty()) {
			a = q[1].front(); q[1].pop();
			b = q[1].front(); q[1].pop();
		} else if(q[1].empty()) {
			a = q[0].front(); q[0].pop();
			b = q[0].front(); q[0].pop();
		} else {
			if(v[q[0].front()] < v[q[1].front()]) {
				a = q[0].front(); q[0].pop();
				if(q[0].empty()) {
					b = q[1].front(); q[1].pop();
				} else if(v[q[0].front()] < v[q[1].front()]) {
					b = q[0].front(); q[0].pop();
				} else {
					b = q[1].front(); q[1].pop();
				}
			} else {
				a = q[1].front(); q[1].pop();
				if(q[1].empty()) {
					b = q[0].front(); q[0].pop();
				} else if(v[q[0].front()] < v[q[1].front()]) {
					b = q[0].front(); q[0].pop();
				} else {
					b = q[1].front(); q[1].pop();
				}
			}
		}

		add_node(a, b);
	}

	dfs(st[n], 0, 1);
	dfs(dr[n], 1, 1);

	long long S = 0;
	for(int i = 1; i <= on; ++i)
		S += v[i] * (long long)rez[i].first;

	fout << S;
	for(int i = 1; i <= on; ++i)
		fout << "\n" << rez[i].first << " " << rez[i].second;

	return 0;
}