Pagini recente » Cod sursa (job #1063541) | Cod sursa (job #1433859) | Cod sursa (job #1089838) | Cod sursa (job #2933126) | Cod sursa (job #824847)
Cod sursa(job #824847)
#include<stdio.h>
#include<queue>
using namespace std;
FILE *f = fopen("huffman.in","r");
FILE *g = fopen("huffman.out","w");
typedef struct _nod
{
long long info;
int poz;
_nod *st,*dr;
} nod;
#define MaxN 1000100
#define MaxP 3
#define ll long long
int N;
ll Sol,SolV[MaxN][MaxP];
queue<pair<int,nod*> > A,B;
inline void init(nod *& a,ll info,int i)
{
a = new nod;
a->info = info;
a->poz = i;
a->st = a->dr = NULL;
}
void citire(void)
{
int a;
fscanf(f,"%d ",&N);
for(int i=1;i<=N;i++)
{
fscanf(f,"%d",&a);
nod *nou;
init(nou,1LL*a,i);
A.push(make_pair(a,nou));
}
}
inline void creare(nod *a,int depth,int nr)
{
if(!a)
return ;
SolV[a->poz][1] = depth;
SolV[a->poz][2] = nr;
creare(a->st,depth+1,nr*2);
creare(a->dr,depth+1,nr*2+1);
}
void Rezolvare(void)
{
int poz = 1;
for(int i=1;i<N;i++)
{
nod *nou = new nod;
if(A.empty() || (!B.empty() && B.front().first < A.front().first))
{
nou->st = B.front().second;
B.pop();
}
else
{
nou->st = A.front().second;
A.pop();
}
if(A.empty() || (!B.empty() && B.front().first < A.front().first))
{
nou->dr = B.front().second;
B.pop();
}
else
{
nou->dr = A.front().second;
A.pop();
}
nou->info = nou->st->info + nou->dr->info;
nou->poz = 0;
Sol += nou->info;
B.push(make_pair(nou->info,nou));
}
creare(B.front().second,0,0);
}
int main()
{
citire();
Rezolvare();
fprintf(g,"%lld\n",Sol);
for(int i=1;i<=N;i++)
fprintf(g,"%lld %lld\n",SolV[i][1],SolV[i][2]);
}