Pagini recente » Cod sursa (job #625353) | Cod sursa (job #2988496) | Cod sursa (job #1479540) | Cod sursa (job #2544778) | Cod sursa (job #2906954)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("huffman.in");
ofstream fout ("huffman.out");
struct {
int st, dr, nivel;
long long valoare;
}arbore[2000001];
int n;
long long rasp;
void dfs(int nod, int nivel, long long valoare) {
if (nod <= n) {
arbore[nod].nivel = nivel;
arbore[nod].valoare = valoare;
return;
}
dfs(arbore[nod].st, nivel + 1, valoare * 2);
dfs(arbore[nod].dr, nivel + 1, valoare * 2 + 1);
}
int main()
{
fin >> n;
for (int i = 1; i <= n; ++i)
fin >> arbore[i].valoare;
fin.close();
int st1 = 1, end1 = n;
int st2 = n + 1, end2 = n;
while (st1 <= end1 || st2 < end2)
{
int st, dr;
if (st1 <= end1 && st2 <= end2) {
if (arbore[st1].valoare <= arbore[st2].valoare) {
st = st1;
st1++;
}
else {
st = st2;
st2++;
}
}
else if (st1 <= end1) {
st = st1;
st1++;
}
else {
st = st2;
st2++;
}
if (st1 <= end1 && st2 <= end2) {
if (arbore[st1].valoare <= arbore[st2].valoare) {
dr = st1;
st1++;
}
else {
dr = st2;
st2++;
}
}
else if (st1 <= end1) {
dr = st1;
st1++;
}
else {
dr = st2;
st2++;
}
end2++;
arbore[end2].st = st;
arbore[end2].dr = dr;
arbore[end2].valoare = arbore[st].valoare + arbore[dr].valoare;
rasp += arbore[end2].valoare;
}
dfs(end2, 0, 1);
fout << rasp << '\n';
for (int i = 1; i <= n; ++i) {
fout << arbore[i].nivel << " " << arbore[i].valoare << '\n';
}
fout.close();
return 0;
}