rt,白嫖的oiwiki上的模板,但是报了段错误,具体是这一行:Htree root = createHuffmanTree(n);
不知道哪里有问题呜呜
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <map>
#include <cmath>
#include <unordered_map>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int sze = 4e5 + 5;
int n;
int arr[sze];
typedef struct HNode {
int weight;
HNode *lchild, *rchild;
} * Htree;
Htree createHuffmanTree(int n) {
Htree forest[sze];
Htree root = NULL;
for (int i = 0; i < n; i++) {
Htree temp;
temp = (Htree)malloc(sizeof(HNode));
temp->weight = arr[i];
temp->lchild = temp->rchild = NULL;
forest[i] = temp;
}
for (int i = 1; i < n; i++) {
int minn = -1, minnSub;
for (int j = 0; j < n; j++) {
if (forest[j] != NULL && minn == -1) {
minn = j;
continue;
}
if (forest[j] != NULL) {
minnSub = j;
break;
}
}
for (int j = minnSub; j < n; j++) {
if (forest[j] != NULL) {
if (forest[j]->weight < forest[minn]->weight) {
minnSub = minn;
minn = j;
} else if (forest[j]->weight < forest[minnSub]->weight) {
minnSub = j;
}
}
}
root = (Htree)malloc(sizeof(HNode));
root->weight = forest[minn]->weight + forest[minnSub]->weight;
root->lchild = forest[minn];
root->rchild = forest[minnSub];
forest[minn] = root;
forest[minnSub] = NULL;
}
}
int getWPL(Htree root, int len) {
if (root == NULL)
return 0;
else {
if (root->lchild == NULL && root->rchild == NULL)
return root->weight * len;
else {
int left = getWPL(root->lchild, len + 1);
int right = getWPL(root->rchild, len + 1);
return left + right;
}
}
}
void solve(){
cin >> n;
for(int i = 0; i < n; i++)
cin >> arr[i];
Htree root = createHuffmanTree(n);
cout << getWPL(root, 0) << '\n';
free(root);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--)
solve();
return 0;
}