Pagini recente » Cod sursa (job #1813156) | Cod sursa (job #2378135) | Cod sursa (job #2383206) | Cod sursa (job #575807) | Cod sursa (job #791986)
Cod sursa(job #791986)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
using namespace std;
#define nmax 1000010
char s[100];
int N, node, crtNode, V[nmax], Q[2][nmax], beg[2], end[2];
int son[2 * nmax][2], lg[nmax];
long long B[nmax], ans, now[2 * nmax];
void DFS(int node, long long val, int length)
{
if(son[node][0])
{
DFS(son[node][0], val * 2, length + 1);
DFS(son[node][1], val * 2 + 1, length + 1);
}
lg[node] = length;
B[node] = val;
}
int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
int i, j;
fgets(s, 100, stdin);
for(i = 0; isdigit(s[i]); i++)
N = N * 10 + s[i] - '0';
beg[0] = 1;
end[0] = 0;
for(i = 1; i <= N; i++)
{
fgets(s, 100, stdin);
for(j = 0; isdigit(s[j]); j++)
V[i] = V[i] * 10 + s[j] - '0';
Q[0][++end[0]] = i;
now[i] = V[i];
}
crtNode = N;
beg[1] = 1;
end[1] = 0;
int pos, crt;
while(end[0] + end[1] >= beg[0] + beg[1])
{
crtNode ++;
for(i = 0; i < 2; i++)
{
pos = -1;
for(j = 0; j < 2; j++)
if(beg[j] <= end[j] && (pos == -1 || now[pos] > now[Q[j][beg[j]]]))
{
pos = Q[j][beg[j]];
crt = j;
}
beg[crt] ++;
now[crtNode] += now[pos];
son[crtNode][i] = pos;
}
Q[1][++end[1]] = crtNode;
}
DFS(crtNode, 0, 0);
for(i = 1; i <= N; i++)
ans += 1LL * now[i] * lg[i];
printf("%lld\n", ans);
for(i = 1; i <= N; i++)
{
printf("%i %lld\n", lg[i], B[i]);
}
return 0;
}