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;
}

 

リリース7件のオリジナルの記事 ウォンの賞賛0 ビュー66

おすすめ

転載: blog.csdn.net/weiweian123321/article/details/103945016