Pagini recente » Cod sursa (job #1141381) | Cod sursa (job #2973829) | Cod sursa (job #2719402) | Cod sursa (job #1940927) | Cod sursa (job #769604)
Cod sursa(job #769604)
#include <stdio.h>
#include <queue>
#include <limits>
#include <fstream>
#include <cstdio>
#define int64 long long int
#define arb node*
using namespace std;
typedef struct node {
int64 frecv;
arb left;
arb right;
int poz;
} node;
queue<arb> A;
queue<arb> Init;
int n;
int64 S;
int V_h[1000001];
int64 V_val[1000001];
ifstream in("huffman.in");
ofstream out("huffman.out", ofstream::binary);
char buff[12];
char rez[20000001];
int get_nr() {
in.getline(buff, 12, '\n');
int tmp = 0;
for (int i = 0; buff[i] != '\0'; i++) {
tmp = tmp * 10 + (buff[i] - '0');
}
return tmp;
}
void read_() {
n = get_nr();
for (int i = 0; i < n; i++) {
arb El = new node();
int x;
x = get_nr();
El->frecv = x;
El->poz = i;
Init.push(El);
}
in.close();
}
void solve_() {
arb El = new node();
El->frecv = numeric_limits<int64>::max();
Init.push(El);
node *El1, *El2, *Fin;
for (int i = 1; i < n; i++) {
if (A.size() == 0 || (A.front())->frecv > (Init.front())->frecv) {
El1 = Init.front();
Init.pop();
}
else {
El1 = A.front();
A.pop();
}
if (A.size() == 0 || (A.front())->frecv > (Init.front())->frecv) {
El2 = Init.front();
Init.pop();
}
else {
El2 = A.front();
A.pop();
}
Fin = new node();
Fin->frecv = El1->frecv + El2->frecv;
Fin->left = El1;
Fin->right = El2;
A.push(Fin);
S += Fin->frecv;
//printf("%lld %lld -> %lld\n", El1->frecv, El2->frecv, Fin->frecv);
}
}
void dfs_(arb H, int h, int64 val) {
if (H->left != NULL) {
dfs_(H->left, h + 1, val << 1);
}
if (H->right != NULL) {
dfs_(H->right, h + 1, (val << 1) + 1);
}
if (H->left == NULL && H->right == NULL) {
V_h[H->poz] = h;
V_val[H->poz] = val;
}
}
void print_() {
//printf("%lld\n", S);
char* buff = rez;
int L;
L = sprintf(buff, "%lld\n", S);
//strncpy(rez, buff, L);
buff += L;
//out.write(buff, L);
for (int i = 0; i < n; i++) {
//printf("%d %lld\n", V_h[i], V_val[i]);
//memset(buff, 0, 10);
L = sprintf(buff, "%d ", V_h[i]);
buff += L;
//out.write(buff, L);
//memset(buff, 0, 10);
L = sprintf(buff, "%lld\n", V_val[i]);
buff += L;
//out.write(buff, L);
}
out.write(rez,buff - rez);
}
int main() {
//freopen("huffman.in", "r", stdin);
//freopen("huffman.out", "w", stdout);
read_();
solve_();
dfs_(A.front(), 0, 0);
print_();
in.close();
return 0;
}