Pagini recente » Cod sursa (job #3253712) | Cod sursa (job #820825) | Cod sursa (job #2256451)
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#include<string.h>
#include<math.h>
#include<map>
using namespace std;
ofstream out("huffman.out");
struct Node{
long long value;
string cod;
Node *right;
Node *left;
};
typedef struct Node *tNode;
struct cmp{
bool operator() (tNode const &p1, tNode const &p2){
return p1->value > p2->value;
}
};
tNode createNode(long long val, tNode left, tNode right){
tNode node=new Node();
node->value=val;
node->right=right;
node->left=left;
node->cod="";
return node;
}
tNode buildTree(){
ifstream in("huffman.in");
priority_queue<tNode,vector<tNode>,cmp> forest;
int n,i;
tNode node1, node2;
long long x,lg=0;
in>>n;
for(i=1;i<=n;i++) {
in>>x;
tNode node=createNode(x,NULL,NULL);
forest.push(node);
}
in.close();
while(forest.size()>1){
node1=forest.top();
forest.pop();
node2=forest.top();
forest.pop();
lg+=node1->value+node2->value;
forest.push( createNode(node1->value+node2->value,node1,node2) );
}
out<<lg<<'\n';
return forest.top();
}
long long dec(string s){
long long sol=0, p=pow(2,s.size());
for(int i=0;i<s.size();i++){
p=p/2;
if(s[i]=='1') sol=sol+p;
}
return sol;
}
vector< string > readTree(tNode node, string s){
vector< pair<int,int> > sol;
queue<tNode>q;
q.push(node);
while(!q.empty()){
tNode node=q.front();
q.pop();
if(node->right==NULL && node->left==NULL)
sol.push_back(node->cod);
if(node->right!=NULL){
node->right->cod=node->cod+"1";
q.push(node->right);
}
if(node->left!=NULL){
node->left->cod=node->cod+"0";
q.push(node->left);
}
}
return sol;
}
int main(){
vector< string > sol=readTree(buildTree(),"");
for(int i=sol.size()-1;i>=0;i--)
out<<sol[i].size()<<" "<<dec(sol[i])<<'\n';
return 0;
}