Pagini recente » Cod sursa (job #2382837) | Cod sursa (job #2133340) | Cod sursa (job #3178656) | Cod sursa (job #376545) | Cod sursa (job #2617403)
#include <fstream>
using namespace std;
const unsigned int N = 1e6+1e2;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
unsigned int nr, n, st[2*N], dr[2*N], p, u, q[2*N], lg[N*2];
unsigned long long codul[2*N], val[2*N];
void reunesc(int x, int y)
{
++nr;
val[nr] = val[x] + val[y];
st[nr] = x;
dr[nr] = y;
q[++u] = nr;
}
void preordine(int x)
{
if (st[x] != 0)
{
codul[st[x]] = 1ll*codul[x]*2;
lg[st[x]] = 1ll + lg[x];
preordine(st[x]);
}
if (dr[x] != 0)
{
codul[dr[x]] = codul[x]*2*1ll + 1ll;
lg[dr[x]] = 1ll + lg[x];
preordine(dr[x]);
}
}
int main()
{
ios::sync_with_stdio(false);
fin >> n;
for (int i = 1; i <= n; i++)
{
fin >> val[i];
}
fin.close();
u = -1;
nr = n;
int i = 3;
reunesc(1, 2);
while (i <= n || p < u)
{
if (i <= n && val[i] <= val[q[p]])
{
if (i < n && val[i+1] <= val[q[p]])
{
reunesc(i, i+1);
i += 2;
}
else
{
reunesc(i++, q[p++]);
}
}
else
{
if (i <= n && (p == u || val[i] <= val[q[p+1]]))
{
reunesc(q[p++], i++);
}
else
{
reunesc(q[p], q[p+1]);
p += 2;
}
}
}
codul[nr] = 1;
preordine(nr);
long long sum = 0;
for (int i = n + 1; i <= nr; i++)
{
sum += val[i]*1ll;
}
fout << sum << '\n';
for (int i = 1; i <= n; i++)
{
fout << lg[i] << ' ' << codul[i] << '\n';
}
fout.close();
return 0;
}