Huffman coding

[code]
//Originally FOUND in Internet
//by RIT2009061 vikesh iiita

//Author: Ujjal Suttra DHar [CSE’08,RUET]

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>

using namespace std;

struct node {
int weight;
char value;
const node *child0;
const node *child1;

node( int c, int i ) {
value = c;
weight = i;
child0 = 0;
child1 = 0;
}

node( const node* c0, const node* c1 ) {
value = 0;
weight = c0->weight + c1->weight;
child0 = c0;
child1 = c1;
}

bool operator<( const node &a ) const {
if(weight ==a.weight)
return value>a.value;
else
return weight >a.weight;
}

void traverse(string code="") const{

if ( child0 ) {
child0->traverse( code + ‘0’ );
child1->traverse( code + ‘1’ );
} else {
cout <<" " <<value <<" ";
cout <<weight;
cout <<" " <<code <<endl;
}
}

};

/*
void count_chars( int *counts )
{
for ( int i = 0 ; i <256 ; i++ )
counts[ i ] = 0;

freopen("input.dat","r",stdin);

char c;
while((c=getchar())!=EOF)
counts[c]++;
}

*/

int main()
{

freopen("input.dat","r",stdin);

int counts[ 256 ];
char a[1000];

gets(a);

for ( int i = 0 ; i <256 ; i++ )
counts[ i ] = 0;

for(int i=0;i<strlen(a);i++)
counts[a[i]]++;

priority_queue < node > q;

for (int i = 0 ; i <256 ; i++ )
if ( counts[ i ] )
q.push( node( i, counts[ i ] ) );

//if you wanna show the queue
/*while(!q.empty()){
cout<<q.top().value<<endl;
q.pop();
}
*/

while ( q.size() >1 ) {
node *child0 = new node( q.top() );
q.pop();
node *child1 = new node( q.top() );
q.pop();
q.push( node( child0, child1 ) );
}

cout <<"CHAR FREQUENCY HOFFMAN-CODE" <<endl;
q.top().traverse();
return 0;
}

[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *