C++数据结构实验4.2 哈夫曼树
作者:互联网
提交评测的代码几乎无注释,原注释的花花绿绿的代码不见了 ,枯了+_+
/**2018数据结构实验4.2 哈夫曼**/
#include<iostream>
#include<string>
using namespace std;
struct Node
{
char val;
int weg;
int d;
Node *lc;
Node *rc;
};
class haTree
{
private:
Node * HList[10001];
int sum;
public:
haTree(int num);
void sort(int num);
Node* rebuild(Node *root, int num);
void find(Node *root, char e, int &depth);
int totalD();
};
int haTree::totalD()
{
return sum;
}
haTree::haTree(int num)
{
sum = 0;
char value;
int weight;
for (int i = 0; i < num; i++)
{
cin >> value >> weight;
HList[i] = new Node;
HList[i]->d = 0;
HList[i]->val = value;
HList[i]->weg = weight;
HList[i]->lc = NULL;
HList[i]->rc = NULL;
}
}
void haTree::sort(int num)
{
if (num == 1)return;
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num - i - 1; j++)
{
if (HList[j]->weg > HList[j + 1]->weg)
{
Node *temp = new Node;
temp = HList[j];
HList[j] = HList[j + 1];
HList[j + 1] = temp;
}
}
}
}
Node* haTree::rebuild(Node *root, int num)
{
one:
if (num == 1)
{
return root;
}
else
{
sort(num);
root = new Node;
root->val = '#';
root->weg = HList[0]->weg + HList[1]->weg;
root->lc = HList[0];
root->rc = HList[1];
HList[0] = root;
HList[1] = HList[num - 1];
num--;
goto one;
}
}
void haTree::find(Node* root, char e, int &depth)
{
if (root == NULL)
{
depth--;
return;
}
else if (root->val == e)
{
root->d = depth;
sum += depth;
return;
}
find(root->lc, e, ++depth);
find(root->rc, e, ++depth);
depth--;
}
int main()
{
int times;
cin >> times;
while (times--)
{
int num;
cin >> num;
haTree h(num);
Node* r = new Node;
r = h.rebuild(r, num);
string Who;
cin >> Who;
for (int i = 0; i < int(Who.length()); i++)
{
int hh = 0;
h.find(r, Who[i], hh);
}
cout << h.totalD() << endl;
}
return 0;
}
weiweian123321 发布了7 篇原创文章 · 获赞 0 · 访问量 42 私信 关注
标签:Node,哈夫曼,4.2,int,C++,num,HList,haTree,root 来源: https://blog.csdn.net/weiweian123321/article/details/103945016