Pagini recente » Cod sursa (job #3287205) | Cod sursa (job #2435507) | Cod sursa (job #3290810) | Cod sursa (job #2752180) | Cod sursa (job #479688)
Cod sursa(job #479688)
#include <fstream>
#include <vector>
#include <deque>
using namespace std;
struct node
{
node *left, *right;
long long count;
int idx;
bool operator<(const node &other) const
{
return this->count < other.count;
}
bool operator>(const node &other) const
{
return this->count > other.count;
}
};
int n;
vector<pair<int, long long> > res;
deque<node *> a, b;
long long df(node *n, int lg, long long cod)
{
if(n->left == NULL)
{
res[n->idx] = make_pair(lg, cod);
return 0;
}
else
{
cod = cod << 1;
return n->count + df(n->left, lg + 1, cod) + df(n->right, lg + 1, cod + 1);
}
}
inline node* pop(deque<node*> &a)
{
node *tmp = a[0];
a.pop_front();
return tmp;
}
inline node* pop()
{
if(a.size() == 0)
return pop(b);
if(b.size() == 0)
return pop(a);
if(a[0]->count <= b[0]->count)
return pop(a);
return pop(b);
}
int main()
{
ifstream cin("huffman.in");
ofstream cout("huffman.out");
long long x;
cin >> n;
res.resize(n);
a.resize(n);
for(int i=0;i<n;++i)
{
cin >> x;
node *n = new node;
n->right = n->left = NULL;
n->count = x;
n->idx = i;
a[i] = n;
}
long long count = 0;
while(a.size() + b.size() > 1)
{
node *s = pop();
node *d = pop();
node *n = new node;
n->count = s->count + d->count;
n->left = s;
n->right = d;
b.push_back(n);
}
node *r = pop();
cout << df(r, 0, 0) << endl;
for(int i=0;i<n;++i)
cout << res[i].first << " " << res[i].second << "\n";
return 0;
}