Pagini recente » Cod sursa (job #2538260) | Cod sursa (job #2767563) | Cod sursa (job #212454) | Cod sursa (job #3237899) | Cod sursa (job #600119)
Cod sursa(job #600119)
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
const char InFile[]="huffman.in";
const char OutFile[]="huffman.out";
const int MaxN=1000111;
ifstream fin(InFile);
ofstream fout(OutFile);
struct nod
{
nod(nod *left=NULL, nod *right=NULL, long long w=0):left(left),right(right),w(w){}
nod *left,*right;
long long w;
};
struct el
{
el(long long cod=0, int l=0):cod(cod),l(l){}
long long cod;
int l;
};
struct cmp_el
{
inline bool operator() (const el &a, const el &b)
{
return a.l>b.l;
}
};
int N,x;
queue<nod*> q1,q2;
vector<el> vsol;
inline nod* getmin()
{
nod *sol=NULL;
if(!q1.empty())
{
sol=q1.front();
}
if(!q2.empty())
{
if(sol)
{
if(sol->w>q2.front()->w)
{
sol=q2.front();
}
}
else
{
sol=q2.front();
}
}
if(!q1.empty())
{
if(sol==q1.front())
{
q1.pop();
}
else
{
q2.pop();
}
}
else
{
q2.pop();
}
return sol;
}
long long dfs(nod *n, long long cod, int l)
{
if(n->left!=NULL && n->right!=NULL)
{
return dfs(n->left,cod<<1,l+1)+dfs(n->right,(cod<<1)+1,l+1)+n->w;
}
else
{
vsol.push_back(el(cod,l));
return 0;
}
}
int main()
{
fin>>N;
for(register int i=1;i<=N;++i)
{
fin>>x;
q1.push(new nod(NULL,NULL,x));
}
fin.close();
while(q1.size()+q2.size()>=2)
{
nod *left=getmin();
nod *right=getmin();
q2.push(new nod(left,right,left->w+right->w));
}
nod *root=getmin();
fout<<dfs(root,0,0)<<"\n";
sort(vsol.begin(),vsol.end(),cmp_el());
for(vector<el>::iterator it=vsol.begin();it!=vsol.end();++it)
{
fout<<it->l<<" "<<it->cod<<"\n";
}
fout.close();
return 0;
}