Pagini recente » Cod sursa (job #1319058) | Cod sursa (job #1982018) | Cod sursa (job #2277857) | Cod sursa (job #384833) | Cod sursa (job #2274008)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
struct nod
{
nod(int val = -1)
{
this->val = val;
ind = -1;
}
void AddChild(nod * x)
{
child.push_back(x);
}
vector<nod*> child;
int val;
int ind;
};
nod* GetMax(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, int> > &rasp, int lg, int x, int &total)
{
for(int i = 0; i < current->child.size(); ++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, int> > rasp(n);
queue<nod*> qElem, qSum;
int 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 = GetMax(qElem, qSum), b = GetMax(qElem, qSum);
t = new nod(a->val + b->val);
t->AddChild(a);
t->AddChild(b);
cout << a->val << " " << b->val << " " << t->val << "\n";
qSum.push(t);
}
t = GetMax(qElem, qSum);
int 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;
}