Pagini recente » Cod sursa (job #2941387) | Cod sursa (job #260257) | Cod sursa (job #1496923) | Cod sursa (job #2453523) | Cod sursa (job #479683)
Cod sursa(job #479683)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
struct node
{
node *left, *right;
long long count;
long long idx;
bool operator<(const node &other) const
{
return this->count < other.count;
}
bool operator>(const node &other) const
{
return this->count > other.count;
}
};
long long n;
priority_queue<node, vector<node>, greater<node> > q;
vector<pair<long long, long long> > res;
long long df(node *n, long long lg, long long cod)
{
if(n->left == NULL)
{
res[n->idx] = make_pair(lg, cod);
return 0;
}
else
return n->count + df(n->left, lg + 1, cod << 1) + df(n->right, lg + 1, (cod << 1) + 1);
}
int main()
{
ifstream cin("huffman.in");
ofstream cout("huffman.out");
long long x;
cin >> n;
res.resize(n);
for(long long i=0;i<n;++i)
{
cin >> x;
node n;
n.right = n.left = NULL;
n.count = x;
n.idx = i;
q.push(n);
}
long long count = 0;
while(q.size() > 1)
{
node *s = new node; *s = q.top(); q.pop();
node *d = new node; *d= q.top(); q.pop();
node n;
n.count = s->count + d->count;
n.left = s;
n.right = d;
q.push(n);
}
node r = q.top();
cout << df(&r, 0, 0) << endl;
for(long long i=0;i<n;++i)
cout << res[i].first << " " << res[i].second << "\n";
return 0;
}