Pagini recente » Cod sursa (job #1352861) | Cod sursa (job #225412) | Cod sursa (job #2699848) | Cod sursa (job #1378781) | Cod sursa (job #2886220)
#include <fstream>
#include <queue>
using namespace std;
const int nmax = 1e6;
queue < int > q1, q2;
struct node {
long long val;
int st, dr;
} a[2 * nmax];
long long code[nmax];
int len[nmax];
int n;
int minim () {
int r;
if ( q2.size () == 0 || ( q1.size() > 0 && a[q1.front()].val < a[q2.front()].val ) ) {
r = q1.front ();
q1.pop ();
} else {
r = q2.front ();
q2.pop ();
}
return r;
}
void dfs ( int node, long long cod, int lun ) {
if ( node == -1 )
return;
if ( node < n ) {
code[node] = cod;
len[node] = lun;
}
dfs ( a[node].st, cod * 2, lun + 1 );
dfs ( a[node].dr, cod * 2 + 1, lun + 1 );
}
ifstream fin ( "huffman.in" );
ofstream fout ( "huffman.out" );
int main() {
fin >> n;
for ( int i = 0; i < 2 * n; i++ )
a[i].st = a[i].dr = -1;
for ( int i = 0; i < n; i++ ) {
fin >> a[i].val;
q1.push ( i );
}
int ind = n;
while ( q1.size() + q2.size() >= 2 ) {
int x = minim (), y = minim ();
a[ind].val = a[x].val + a[y].val;
a[ind].st = x;
a[ind].dr = y;
q2.push ( ind );
ind++;
}
dfs ( ind - 1, 0, 0 );
long long s = 0;
for ( int i = 0; i < n; i++ )
s += ( long long ) a[i].val * len[i];
fout << s << '\n';
for ( int i = 0; i < n; i++ )
fout << len[i] << ' ' << code[i] << '\n';
return 0;
}