Pagini recente » Cod sursa (job #1412771) | Cod sursa (job #2351322) | Istoria paginii runda/summer2019/clasament | Cod sursa (job #553511) | Cod sursa (job #2886213)
#include <fstream>
#include <queue>
using namespace std;
const int nmax = 1e6;
queue < pair < long long, int > > q1, q2;
struct node {
int st, dr;
} a[2 * nmax];
long long code[2 * nmax];
int len[2 * nmax];
int f[nmax];
pair < long long, int > minim () {
pair < long long, int > r;
if ( q2.size () == 0 || ( q1.size() > 0 && q1.front() < q2.front() ) ) {
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;
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() {
int n;
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 >> f[i];
q1.push ( { f[i], i } );
}
int ind = n;
while ( q1.size() + q2.size() >= 2 ) {
auto x = minim (), y = minim ();
a[ind].st = x.second;
a[ind].dr = y.second;
q2.push ( { x.first + y.first, ind } );
ind++;
}
dfs ( ind - 1, 0, 0 );
long long s = 0;
for ( int i = 0; i < n; i++ )
s += ( long long ) f[i] * len[i];
fout << s << '\n';
for ( int i = 0; i < n; i++ )
fout << len[i] << ' ' << code[i] << '\n';
return 0;
}