#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的最小两个结点
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<< "输入哈夫曼树叶子节点数";
cin >>n;
cout<< endl;
INIT(T,n);
BuildHuffman(T, n);
Show(T,n);
}
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
文章标题:c++哈夫曼树实现-创新互联
文章起源:https://www.cdcxhl.com/article38/ddossp.html
成都网站建设公司_创新互联,为您提供标签优化、品牌网站设计、网站设计、用户体验、网站排名、响应式网站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联