1. 程式人生 > >用n個帶權值構造的哈夫曼樹的帶權路徑長度

用n個帶權值構造的哈夫曼樹的帶權路徑長度

//哈夫曼樹
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

typedef struct
{
	int data;
	int parent;
	int leftChild, rightChild;
}node;//data是數值、其他的存陣列下標
node *treee;

int Huffman(int *a, int n)
{
	int ans = 0;
	node tree[200];//陣列+指標,十字連結串列法?!

	int m = 2 * n - 1;                              //節點總數

	for (int i = 0; i < n; i++)
		tree[i].data = a[i];

	for (int i = 0; i < m; i++)                      //初始化每個節點
	{
		tree[i].parent = NULL;
		tree[i].leftChild = NULL;
		tree[i].rightChild = NULL;
	}
	for (int i = n; i < m; i++)                      //非葉子節點
	{
		int min1 = 1000000, min2 = 1000000;
		int pos1=0, pos2=0;                             //第一小和第二小
		for (int j = 0; j < i; j++)                  //葉子節點
		{
			if (tree[j].parent == NULL)//還沒進構成樹的結點
			{
				if (tree[j].data < min1)
				{
					//swap();
					pos2 = pos1;
					pos1 = j;
					min2 = min1;
					min1 = tree[j].data;
				}
				else if (tree[j].data < min2)
				{
					min2 = tree[j].data;
					pos2 = j;
				}
			}
		}
		tree[i].leftChild = min(pos1, pos2);
		tree[i].rightChild = max(pos1, pos2);
		tree[i].data = tree[pos1].data + tree[pos2].data;
		tree[pos1].parent = i;
		tree[pos2].parent = i;
		ans += tree[i].data;
	}
	treee = tree;//為了把構造好的哈夫曼樹用全域性變數傳遞出來
	return ans;//哈夫曼樹最小權值
}


int main()
{
	int num[120];
	int n;
	cout << "比如:用5個帶權值{3,2,4,5,1}構造的哈夫曼樹的帶權路徑長度" << endl;
	//n個數字,排列出哈夫曼樹
	cout << "請輸入要輸入的元素的個數" << endl;
	cin >> n;
	cout << "請輸入各個元素的值(非負數)" << endl;
	for (int i = 0; i < n; i++)
		cin >> num[i];

	cout << "所得結果:"<<Huffman(num, n) << endl;
}