Pagini recente » Cod sursa (job #3040534) | Cod sursa (job #2524644) | Cod sursa (job #58305) | Cod sursa (job #1155582) | Cod sursa (job #2274021)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
struct nod
{
nod(long long val = -1)
{
this->val = val;
ind = -1;
child[0] = child[1] = NULL;
}
void AddChildren(nod * x, nod * y)
{
child[0] = x, child[1] = y;
}
nod * child[2];
long long val;
int ind;
};
nod* GetMin(queue<nod*> &a, queue<nod*> &b)
{
nod * ret;
if(a.empty() == false && (b.empty() == true || a.front()->val < b.front()->val))
{
ret = a.front();
a.pop();
}
else
{
ret = b.front();
b.pop();
}
return ret;
}
void DFS(const nod * current, vector<pair<int, long long> > &rasp, int lg, long long x, long long &total)
{
if(current->child[0] != NULL)
{
for(int i = 0; i < 2; ++i)
DFS(current->child[i], rasp, lg+1, (x << 1) + i, total);
}
if(current->ind != -1)
rasp[current->ind] = make_pair(lg, x);
else
total += current->val;
}
int main()
{
ifstream in("huffman.in");
int n;
in >> n;
vector<pair<int, long long> > rasp(n);
queue<nod*> qElem, qSum;
long long x;
nod * t;
for(int i = 0; i < n; ++i)
{
in >> x;
t = new nod(x);
t->ind = i;
qElem.push(t);
}
in.close();
nod *a, *b;
while(qElem.size() + qSum.size() > 1)
{
a = GetMin(qElem, qSum), b = GetMin(qElem, qSum);
t = new nod(a->val + b->val);
t->AddChildren(a, b);
qSum.push(t);
}
t = GetMin(qElem, qSum);
long long total = 0;
DFS(t, rasp, 0, 0, total);
ofstream out("huffman.out");
out << total << "\n";
for(int i = 0; i < n; ++i)
out << rasp[i].first << " " << rasp[i].second << "\n";
out.close();
return 0;
}