Pagini recente » Cod sursa (job #2948898) | Cod sursa (job #3295318) | preoni-2007/runda-finala/poze/la-masa | Cod sursa (job #453434) | Cod sursa (job #812438)
Cod sursa(job #812438)
#include <fstream>
#include <queue>
using namespace std;
const int Nmax = 1000010;
const int Smax = 2000010;
int N,V[Nmax];
long long C[Nmax],Lung;
int L[Nmax];
struct Huffman
{
int Val , Key;
int Lson, Rson , Dad;
};
char Chr[Nmax];int Sz;
Huffman A[Smax];
int Size;
#define val first
#define key second
typedef pair<int,int> Pair;
priority_queue< Pair , vector<Pair> , greater<Pair> > MinH;
ifstream F("huffman.in");
ofstream G("huffman.out");
void DFS(int pl,int lung,long long val)
{
if ( pl <= N ) C[ pl ]=val , L[ pl ]=lung , Lung += 1LL * V[pl] * lung;
if ( A[pl].Lson ) DFS(A[pl].Lson,lung+1,2*val);
if ( A[pl].Rson ) DFS(A[pl].Rson,lung+1,2*val+1);
}
int main()
{
F>>N, Size = N;
for (int i=1;i<=N;++i)
{
F>>V[i];
A[i].Key = i;
A[i].Val = V[i];
A[i].Lson = 0;
A[i].Rson = 0;
MinH.push( make_pair( V[i] , i ) );
}
while ( MinH.size() > 1 )
{
Pair P1 = MinH.top(); MinH.pop();
Pair P2 = MinH.top(); MinH.pop();
Pair P3 = make_pair( P1.val + P2.val , ++Size );
MinH.push( P3 );
A[Size].Key = P3.key;
A[Size].Val = P3.val;
A[Size].Lson = P1.key;
A[Size].Rson = P2.key;
A[P1.key].Dad = A[Size].Key;
A[P2.key].Dad = A[Size].Key;
}
DFS(Size,0,0);
G<<Lung<<'\n';
for (int i=1;i<=N;++i)
G<<L[i]<<' '<<C[i]<<'\n';
}