#include
using namespace std;
struct Tpoint {
?int weight;
?int lchild;
?int rchild;
?int parent;
};
void INIT(Tpoint* T,int n) { ? ? ? ? ? ? ? ? ? ? ? ?//初始化哈夫曼樹
?for (int i = 1; i<= 2 * n - 1; i++) {
??? ?T[i].lchild = 0;
??? ?T[i].rchild = 0;
??? ?T[i].parent = 0;
?}
?int weight;
?for (int i = 1; i<= n; i++) {
??? ?cin >>weight;
??? ?T[i].weight = weight;
?}
}
void Show(Tpoint* T,int n) { ? ? //展示二叉樹
?for (int i = 1; i<= ?2 * n - 1; i++) {
??? ?cout<< i<<"\t"<
}
void SelectMin(Tpoint* T, int n, int& m1, int& m2) { ?//找到i之前且雙親為0的最小兩個結(jié)點
?for (int i = 1; i<= n; i++) {
??? ?if (T[i].parent != 0)
??? ??? ?continue;
??? ?if (T[m1].weight >T[i].weight)
??? ??? ?m1 = i;
?}
?for (int i = 1; i<= n; i++) {
??? ?if (T[i].parent != 0 || i == m1)
??? ??? ?continue;
??? ?if (T[m2].weight >T[i].weight)
??? ??? ?m2 = i;
?}
}
void BuildHuffman(Tpoint* T, int n) { ?//生成huffman樹
?int m1=1, m2;
?for (int i = n + 1; i<= 2 * n - 1; i++) {
??? ?m1 = 0, m2 = 0;
??? ?SelectMin(T, i - 1, m1, m2);
??? ?T[m1].parent = i ;
??? ?T[m2].parent = i ;
??? ?T[i].lchild = m1;
??? ?T[i].rchild = m2;
??? ?T[i].weight = T[m1].weight + T[m2].weight;
?}
}
int main() {
?Tpoint T[100];
?T[0].weight = 1000;
?int n;
?cout<< "輸入哈夫曼樹葉子節(jié)點數(shù)";
?cin >>n;
?cout<< endl;
?INIT(T,n);
?BuildHuffman(T, n);
?Show(T,n);
}
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧