#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<iomanip.h>
const MAX=55;
class m_heap //a min heap
{ private:
int T[MAX],N,loc[MAX];//coz we take here,d sequential representation of trees here;
public:
m_heap()
{ N=0;
}
void insert(int item,int l)
{ N++;
int ptr=N,par;
while(ptr>1)
{ par=ptr/2;
if(item>=T[par])
{ T[ptr]=item;
loc[ptr]=l;
return;
}
T[ptr]=T[par];
loc[ptr]=loc[par];
ptr=par;
};
T[1]=item;
loc[1]=l;
}
void Sdis()
{ for(int i=1;i<=N;i++)
cout<<endl<<setw(9)<<T[i]<<setw(9)<<loc[i];
}
int del(int &lo)
{ int item=T[1],l=loc[1],last=T[N],ll=loc[N],ptr=1,left=2,right=3;
N--;
while(right<=N)
{ if(last<=T[left] && last<=T[right])
{T[ptr]=last;
loc[ptr]=ll;
break;
}
if(T[right]>=T[left])
{ T[ptr]=T[left];
loc[ptr]=loc[left];
ptr=left;
}
else
{T[ptr]=T[right];
loc[ptr]=loc[right];
ptr=right;
}
left=2*ptr;
right=left+1;
};
if(left==N && last>T[left])
{ptr=left;
T[1]=T[left];
loc[1]=loc[left];
}
T[ptr]=last;
loc[ptr]=ll;
lo=l;
return item;
}
int retN()
{ return N;
}
};
class hoffman
{ private:
int wt[MAX],left[MAX],right[MAX],n;
char info[MAX];
public:
void insert()
{ cout<<"Enter the no. of external nodes u want:";
cin>>n;
cout<<"\nEnter information and weight in order(info wt):";
for(int i=1;i<=n;i++)
{ cin>>info[i]>>wt[i];
left[i]=0;
right[i]=0;
}
}
void dis()
{
cout<<"s.no"<<setw(9)<<"INFO"<<setw(9)<<"WEIGHT"<<setw(9)<<"LEFT"<<setw(9)<<"RIGHT";
for(int i=1;i<=n;i++)
cout<<endl<<i<<" "<<info[i]<<setw(9)<<wt[i]<<setw(9)<<left[i]<<setw(9)<<right[i];
}
void hoff()
{ m_heap H;
int w1,w2,l1,l2;
for(int i=1;i<=n;i++)
H.insert(wt[i],i);
while(1)
{ if(H.retN()==0)
{ n--;
break;
}
w1=H.del(l1);
w2=H.del(l2);
n++;
wt[n]=w1+w2;
left[n]=l1;
right[n]=l2;
info[n]=' ';
H.insert(wt[n],n);
}
}
};
void main()
{ clrscr();
hoffman H;
H.insert();
g:
clrscr();
cout<<"HOFFMAN menu:";
cout<<"\n1.> display";
cout<<"\n2.> Create Hoffman's tree";
cout<<"\n3.> Exit";
cout<<"\nEnter your choice:";
char ch;
cin>>ch;
switch(ch)
{ case '1':clrscr();
H.dis();
getch();
goto g;
case '2':clrscr();
H.hoff();
getch();
goto g;
default: exit(0);
};
getch();
}
No comments:
Post a Comment