Pagini recente » Cod sursa (job #1779526) | Cod sursa (job #1466486) | Cod sursa (job #2380758) | Cod sursa (job #3156442) | Cod sursa (job #791990)
Cod sursa(job #791990)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
using namespace std;
#define nmax 1000010
char s[1 << 18];
int N, node, crtNode, V[nmax], Q[2][nmax], beg[2], end[2], nowpos;
int son[2 * nmax][2], lg[nmax];
long long B[nmax], ans, now[2 * nmax];
void verify()
{
if(s[nowpos] == 0)
{
fgets(s, 1 << 18, stdin);
nowpos = 0;
}
}
int get()
{
int nr = 0;
while(!isdigit(s[nowpos]))
nowpos ++, verify();
while(isdigit(s[nowpos]))
nr = nr * 10 + s[nowpos] - '0', nowpos ++, verify();
return nr;
}
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);
return ;
}
lg[node] = length;
B[node] = val;
}
int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
int i, j;
verify();
N = get();
beg[0] = 1;
end[0] = 0;
for(i = 1; i <= N; i++)
{
V[i] = get();
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;
}