Pagini recente » Diferente pentru problema/diviz intre reviziile 1 si 2 | Cod sursa (job #1701685)
#include<iostream>
#include<fstream>
#include<queue>
using namespace std;
ifstream f("huffman.in");
ofstream g("huffman.out");
int const NMax = 1001000;
long long V[2*NMax], C[2*NMax];
int G[2*NMax][3], L[2*NMax];
long long n, nr, lg, st1, st2, dr1, dr2;
int Q1[NMax], Q2[2*NMax];
long long const oo = 1LL<<62;
void Read()
{
f>>n;
for(int i=1; i<=n; i++)
f>>V[i];
}
inline int GetMin()
{
int x, y;
x = Q1[st1]; y = Q2[st2];
if(V[x] < V[y]){
st1++;
return x;
}
else{
st2++;
return y;
}
}
void DFS(int nod, long long cod, bool side)
{
if(G[nod][0] == 0){
C[nod] = (cod << 1) + side;
return;
}
lg += V[nod];
cod = (cod << 1) + side;
int son1, son2;
son1 = G[nod][0];
son2 = G[nod][1];
L[son1] = L[son2] = L[nod] + 1;
DFS(G[nod][0], cod, 0);
DFS(G[nod][1], cod, 1);
}
void Solve()
{
int i, x, y;
for(i=1; i<=n; i++)
Q1[++dr1] = i;
nr = n;
st1 = st2 = 1;
dr2 = 0;
V[0] = oo;
while((dr1 - st1 + 1) + (dr2 - st2 + 1) > 1){
nr++;
x = GetMin();
y = GetMin();
V[nr] = V[x] + V[y];
Q2[++dr2] = nr;
G[nr][0] = x;
G[nr][1] = y;
}
//DFS(nr, 0, 0);
}
void Print()
{
g<<lg<<"\n";
for(int i=1; i<=n; i++)
g<<L[i]<<" "<<C[i]<<"\n";
}
int main()
{
Read();
Solve();
Print();
return 0;
}