#include<iostream>using namespace std;struct element{ int weight; int lchild, rchild, parent;};void Select(element hfmt[], int &i1, int &i2, int &num){ element hfmtw[7]; int min; bool isi1 = false; for (int i = 0; i<num; i++) { hfmtw[i] = hfmt[i]; } int temp; for (int a = 0; a<num - 1; a++){ if (hfmtw[a].parent != -1){ continue; } min = a; for (int j = a; j<num; j++){ if (hfmtw[j + 1].weight<hfmtw[min].weight) { if (hfmtw[j + 1].parent != -1){ continue; } min = j + 1; } } if (isi1 == false){ i1 = min; isi1 = true; } else{ i2 = min; return; } temp = hfmtw[a].weight; hfmtw[a].weight = hfmtw[min].weight; hfmtw[min].weight = temp; } num++;}void Hfmt(element hfmt[], int w[], int n){ for (int i = 0; i<2 * n - 1; i++){ hfmt[i].parent = -1; hfmt[i].lchild = -1; hfmt[i].rchild = -1; } for (int b = 0; b<n; b++){ hfmt[b].weight = w[b]; } int i1 = 0, i2 = 0; int num = n; for (int k = n; k<2 * n - 1; k++) { Select(hfmt, i1, i2, num); hfmt[i1].parent = k; hfmt[i2].parent = k; hfmt[k].weight = hfmt[i1].weight + hfmt[i2].weight; hfmt[k].lchild = i1; hfmt[k].rchild = i2; }}void main(){ element hfmt[7]; int n = 4; int w[] = { 2, 3, 4, 5 }; Hfmt(hfmt, w, n); for (int i=0; i<7; i++) { cout << hfmt[i].weight << " " << hfmt[i].parent << " " << hfmt[i].lchild << " " << hfmt[i].rchild << endl; }}怎么跟预计的不一样
1 回答
- 1 回答
- 0 关注
- 1364 浏览
添加回答
举报
0/150
提交
取消