哈夫曼树
#include<vector> #include<cstdio> #include<iostream> #include<algorithm> using namespace std; struct HT { int weight, parent, l, r, idx; }; bool cmp(HT a, HT b) { return a.weight < b.weight; } int main() { int n; vector<HT>a, b; cin >> n; for (int i = 0; i < n; i++) { HT x; cin >> x.weight; x.idx = i; x.parent = -1; x.l = -1; x.r = -1; a.push_back(x); b.push_back(x); } while (a.size() != 1) { sort(a.begin(), a.end(), cmp); HT x; x.idx = b.size(); x.weight = a[0].weight + a[1].weight; x.l = a[0].idx; x.r = a[1].idx; for (int i = 0; i < b.size(); i++) { if (b[i].idx == x.l || b[i].idx == x.r) b[i].parent = x.idx; } a.push_back(x); a.erase(a.begin()); a.erase(a.begin()); b.push_back(x); } b[b.size() - 1].parent = -1; for (int i = 0; i < b.size(); i++) printf("%d %d %d %d %d\n", b[i].idx, b[i].l, b[i].weight, b[i].r, b[i].parent); return 0; }