Cod sursa(job #2614045)

Utilizator CyborgSquirrelJardan Andrei CyborgSquirrel Data 11 mai 2020 09:14:20
Problema Coduri Huffman Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#include <queue>

using namespace std;

typedef long long lint;

struct Node{
	int ch[2];
	lint val;
	
	lint code, len;
};

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

int n;
Node nodes[2000041];

queue<int> inter;
void read(){
	fin >> n;
	for(int i = 1; i <= n; ++i){
		int a;fin >> nodes[i].val;
	}
}

lint ans = 0;
void solve(){
	int init = 1;
	for(int i = n+1; i <= 2*n-1; ++i){
		Node &node = nodes[i];
		for(int j = 0; j < 2; ++j){
			int ch;
			if(inter.empty() || (init <= n && nodes[init].val < nodes[inter.front()].val)){
				ch = init;
				init++;
			}else{
				ch = inter.front();
				inter.pop();
			}
			node.ch[j] = ch;
			node.val += nodes[ch].val;
		}
		ans += node.val;
		inter.push(i);
	}
}

queue<int> quu;
void write(){
	fout << ans << "\n";
	quu.push(2*n-1);
	while(!quu.empty()){
		Node &node = nodes[quu.front()];
		quu.pop();
		for(int i = 0; i < 2; ++i){
			int ch = node.ch[i];
			nodes[ch].len = node.len+1;
			nodes[ch].code = (node.code<<1) + i;
			if(ch > n){
				quu.push(ch);
			}
		}
	}
	for(int i = 1; i <= n; ++i){
		fout << nodes[i].len << " " << nodes[i].code << "\n";
	}
}

int main(){
	// ios_base::sync_with_stdio(false);
	read();
	solve();
	write();
	return 0;
}