Pagini recente » Cod sursa (job #2764830) | Cod sursa (job #1971247) | Cod sursa (job #2917920) | Cod sursa (job #2945758) | Cod sursa (job #2620811)
#include <fstream>
#include <queue>
using namespace std;
const int N = 2e6 + 1;
ifstream in("huffman.in");
ofstream out("huffman.out");
int n, nr, st[N], dr[N], nivel[N];
long long val[N], cod[N];
queue <int> q1, q2;
int selectie()
{
int minim;
if (q1.empty())
{
minim = q2.front();
q2.pop();
return minim;
}
if (q2.empty())
{
minim = q1.front();
q1.pop();
return minim;
}
if (val[q1.front()] <= val[q2.front()])
{
minim = q1.front();
q1.pop();
}
else
{
minim = q2.front();
q2.pop();
}
return minim;
}
void adauga(int x, int y)
{
val[++nr] = val[x] + val[y];
st[nr] = x;
dr[nr] = y;
q2.push(nr);
}
long long rsd(int x)
{
long long suma = 0;
if (st[x] != 0)
{
cod[st[x]] = cod[x] * 2;
nivel[st[x]] = 1 + nivel[x];
cod[dr[x]] = cod[x] * 2 + 1;
nivel[dr[x]] = 1 + nivel[x];
suma += val[x] + rsd(st[x]) + rsd(dr[x]);
}
return suma;
}
int main()
{
in >> n;
for (int i = 1; i <= n; i++)
{
in >> val[i];
q1.push(i);
}
in.close();
nr = n;
while (q1.size() + q2.size() > 1)
{
int x = selectie();
int y = selectie();
adauga(x, y);
}
out << rsd(nr) << "\n";
for (int i = 1; i <= n; i++)
{
out << nivel[i] << " " << cod[i] << "\n";
}
out.close();
return 0;
}