1.问题描述:把N个已分类的文件通过成对地重复归并已分类的文件归并在一个文件中。例如,假定X1,X2,X3,X4是要归并的文件,则可以首先把X1,X2归并成Y1,然后Y1和X3归并成Y2,最后Y2和X4归并,从而得到要的分类文件。运用最优二路归并方法,归并出来的结果都有想对应的最小权带外部路径的二元树,所以把问题转换为由N棵根结点带权值的树组成的森林,归并成为一棵二元树。
2.设计思想与分析:
基本思路:(1)假设给定的一组权值{W1,W2,……,Wn},由此可以产生出由N棵二元树组成的森林F={T1,T2,……,Tn},其中每棵树都有一个权值为Wi的根结点;(2)在森林F中选出两棵树根结点的权值最小的树,作为一棵新树的左右子树且置新树的根结点的权值为其左右子树的根结点的权值之和;(3)从森林F中删去分别做为左右子树的这两棵树,同时将新树加入到集合F中;(4)对新的森林重复2,3步骤,直到F中只剩一棵二元树时为止,这就是所要的树了。
#include "iostream.h"
struct HuffmanNode
{
int weight;
int parent;
int lchild,rchild;
};////////////////////////////////structure of node
///////////////////////////////////////////////////
class HuffmanTree
{
public:
HuffmanNode *Node;
public:
Tree(int weightnum);
};////////////////////////////////huaffmantree class
////////////////////////////////////////////////////
HuffmanTree::Tree(int weightnum)
{
int i , j, pos1,pos2;
int min1,min2;
Node=new struct HuffmanNode [2*weightnum-1];
for (i=0;i<weightnum;i++)
{
cout<<"请输入第"<<i+1<<"个字符的权值:";
cin>>Node[i].weight;
Node[i].parent=-1;
Node[i].lchild=-1;
Node[i].rchild=-1;
}
/////////////////////*join and creat tree*///////////////
for (i=weightnum; i<2*weightnum-1; i++) {
pos1=-1; pos2=-1;
min1=min2=32762;
j=0;
while(j<=i-1)
{
if (Node[j].parent==-1)
{
if(Node[j].weight<=min1)
{ min2=min1; min1=Node[j].weight;
pos2=pos1; pos1=j; }
else
if(Node[j].weight<min2)
{ min2=Node[j].weight; pos2=j; }
}
j++;
}//while
Node[pos1].parent=i;
Node[pos2].parent=i;
Node[i].lchild=pos1;
Node[i].rchild=pos2;
Node[i].parent=-1;
Node[i].weight=Node[pos1].weight+Node[pos2].weight;
}//for
j=2*weightnum-2;
int l,r;
while(Node[j].lchild!=-1||Node[j].rchild!=-1)
{
cout<<"root is:"<<Node[j].weight<<" ";
l=Node[j].lchild;
r=Node[j].rchild;
cout<<"lchild is:"<<Node[l].weight<<" ";
cout<<"rchild is:"<<Node[r].weight<<" ";
cout<<endl;
j--;
}
} //////////////////////////////////creat a Btree
///////////////////////////////////////////////
void main()
{ cout<<"|--------生成最优的二元归并树---------|"<<endl;
cout<<"|---power by zhanjiantao(028054115)---|"<<endl;
cout<<"|-------------------------------------|"<<endl;
int i;
while(i)
{
int weightnum;
cout<<"请输入权值的个数: ";
cin>>weightnum;
HuffmanTree t;
t.Tree(weightnum);
cout<<"Press<1> to run again"<<endl;
cout<<"Press<0> to exit"<<endl;
cin>>i;
}
}