Pagini recente » Cod sursa (job #745822) | Cod sursa (job #180777) | Cod sursa (job #3288462) | Cod sursa (job #186181) | Cod sursa (job #597154)
Cod sursa(job #597154)
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
#define MAX 1000010
struct node
{
node *left, *right;
int c, weight;
};
class comparator
{
public:
bool operator()(node* A, node* B)
{
return A->weight > B->weight; // sau ">" ?
}
};
priority_queue<node*, vector<node*>, comparator> Q;
int code[MAX], length[MAX], total, N;
void df(node *r, int c, int d)
{
if ( r->c > 0 )
{
code[r->c] = c;
length[r->c] = d;
total += r->weight * d;
return ;
}
if ( r->left )
df(r->left, c, d+1);
if ( r->right )
df(r->right, c + (1<<d), d+1);
}
int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
scanf("%d", &N);
for (int i=1; i<=N; ++i)
{
node *p = new node;
scanf("%d", &p->weight);
p->c = i;
p->left = p->right = NULL;
Q.push(p);
}
while ( Q.size() > 1 )
{
node *a = Q.top(); Q.pop();
node *b = Q.top(); Q.pop();
node *c = new node;
c -> weight = a->weight + b->weight;
c -> c = -1;
c -> left = a;
c -> right = b;
Q.push(c);
}
node *root = Q.top(); Q.pop();
df(root, 0, 0);
printf("%d\n", total);
for (int i=1; i<=N; ++i)
printf("%d %d\n", length[i], code[i]);
return 0;
}