Pagini recente » Cod sursa (job #416208) | Cod sursa (job #502665) | Cod sursa (job #637313) | Cod sursa (job #1348340) | Cod sursa (job #994616)
Cod sursa(job #994616)
#include <iostream>
#include <fstream>
#include <queue>
#include <cstring>
using namespace std;
const int Nmax = 1000005;
struct nod
{
long long v;
int sons[2];
} Arb[2 * Nmax];
queue <int> Q1, Q2;
long long b[Nmax];
int lg[Nmax];
int N;
long long lungime;
void read()
{
ifstream f("huffman.in");
f >> N;
string file( ( istreambuf_iterator <char>( f ) ), istreambuf_iterator<char>( ) );
long long l = file.length();
long long nr = 0;
int index = 1;
for ( long long i = 1; i < l; ++i )
if ( isdigit( file[i] ) )
nr = nr * 10 + ( file[i] - 48 );
else
{
Arb[ index++ ].v = nr;
Q1.push( index - 1 );
nr = 0;
}
f.close();
}
inline int indice()
{
if ( !Q1.empty() && !Q2.empty() )
{
if ( Arb[Q1.front()].v < Arb[Q2.front()].v )
{
int val = Q1.front();
Q1.pop();
return val;
}
else
{
int val = Q2.front();
Q2.pop();
return val;
}
}
if ( Q1.empty() )
{
int val = Q2.front();
Q2.pop();
return val;
}
if ( Q2.empty() )
{
int val = Q1.front();
Q1.pop();
return val;
}
}
void solve()
{
int n = N;
for ( int i = 1; i < N; ++i )
{
int ind1, ind2;
ind1 = indice();
ind2 = indice();
n++;
Arb[n].v = Arb[ind1].v + Arb[ind2].v;
Arb[n].sons[0] = ind1;
Arb[n].sons[1] = ind2;
Q2.push( n );
}
}
void DFS( int root, long long code, int nivel )
{
if ( Arb[root].sons[0] )
{
DFS( Arb[root].sons[0], 2 * code, nivel + 1 );
DFS( Arb[root].sons[1], 2 * code + 1, nivel + 1 );
}
else
{
lg[root] = nivel;
b[root] = code;
lungime += lg[root] * Arb[root].v;
}
}
void print()
{
ofstream g("huffman.out");
g << lungime << "\n";
for ( int i = 1; i <= N; ++i )
{
g << lg[i] << " " << b[i] << "\n";
}
g.close();
}
int main()
{
read();
solve();
DFS( 2 * N - 1, 0, 0 );
print();
return 0;
}