Pagini recente » Borderou de evaluare (job #1567644) | Cod sursa (job #85278) | Cod sursa (job #2164707) | Cod sursa (job #1477505) | Cod sursa (job #2679245)
#include <fstream>
#include <queue>
#include <vector>
#include <utility>
#include <stack>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
const int NMAX = 1000003;
struct Node{
int st_index, dr_index, index;
long long int val;
};
queue<Node>q1;
queue<Node>q2;
Node nodes[2 * NMAX];
pair<Node, Node> take_nodes()
{
Node n1, n2;
int t =2;
vector<Node>b;
while(t--){
if(!q1.empty() && !q2.empty())
{
if(q1.front().val >= q2.front().val)
{
n1 = q2.front();
q2.pop();
b.push_back(n1);
}
else{
n1 = q1.front();
q1.pop();
b.push_back(n1);
}
continue;
}
if(q1.empty())
{
n1 = q2.front();
q2.pop();
b.push_back(n1);
continue;
}
if(q2.empty())
{
n1 = q1.front();
q1.pop();
b.push_back(n1);
continue;
}
}
n1 = b[0];
n2 = b[1];
return make_pair(n1, n2);
}
int huffman(int k)
{
while(q1.size() + q2.size()!= 1)
{
Node n1;
Node n2;
pair <Node, Node> pi = take_nodes();
n1 = pi.first;
n2 = pi.second;
Node n3;
n3.dr_index = n1.index;
n3.st_index = n2.index;
n3.index = k;
n3.val = n1.val + n2.val;
// nodes.push_back(n3);
nodes[k] = n3;
k++;
q2.push(n3);
}
return k;
}
vector<pair<long long int, long long int> >sol;
void dfs(int index, long long int depth, long long int x, int k)
{
if(nodes[index].index < k)
{
sol[nodes[index].index].first = depth;
sol[nodes[index].index].second = x;
return;
}
else{
dfs(nodes[index].st_index, depth + 1, ((x<<1)|0), k);
dfs(nodes[index].dr_index, depth + 1, ((x<<1)|1), k);
}
}
int main()
{
int n, i, j, k, x;
Node aux;
aux.dr_index = -1;
aux.st_index = -1;
fin>>n;
k = 0;
for(i=0;i<n;i++)
{
fin>>x;
aux.index = k;
k++;
aux.val = x;
//nodes.push_back(aux)
nodes[i] = aux;
q1.push(aux);
sol.push_back(make_pair(0, 0));
}
int ck = k;
k = huffman(k);
long long sum = 0;
for(i = ck; i < k; i++)
sum = sum + nodes[i].val;
fout<<sum<<"\n";
dfs(k-1, 0, 0, ck);
for(i =0; i < sol.size(); i++)
{
fout<<sol[i].first <<" "<<sol[i].second<<"\n";
}
return 0;
}