Pagini recente » Cod sursa (job #376390) | Cod sursa (job #196171) | Cod sursa (job #2815101) | Cod sursa (job #1014152) | Cod sursa (job #2619386)
#include <bits/stdc++.h>
#define N 1000005
using namespace std;
int n, on, v[2*N], st[2*N], dr[2*N];
queue<int> q[2];
pair<int, int> 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, int cv, int cvs) {
if(st[x]) {
dfs(st[x], (cv << 1), cvs+1);
dfs(dr[x], (cv << 1) + 1, 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);
int S = 0;
for(int i = 1; i <= on; ++i)
S += v[i] * rez[i].first;
fout << S;
for(int i = 1; i <= on; ++i)
fout << "\n" << rez[i].first << " " << rez[i].second;
return 0;
}