链表实现
时间复杂度:O(n)
#include <bits/stdc++.h>
#define maxn 1005
using namespace std;
struct node* create(char *ch, int *w, int n);
void print(struct node* root, string res);
struct node {
char data;
int weight;
struct node *left, *right;
};
struct cmp {
bool operator()(node*a, node*b) {
if (a->weight == b->weight)
return a->data > b->data;
return a->weight > b->weight;
}
};
int n;
char ch[maxn];
int weight[maxn];
int main() {
cout << "请输入字符个数: " << endl;
cin >> n;
cout << "请一次输入每个字符以及其出现的次数: " << endl;
for (int i = 0; i < n; i++) {
cin >> ch[i];
cin >> weight[i];
}
struct node* root = create(ch, weight, n);
print(root, "");
system("pause");
return 0;
}
struct node* create(char *ch, int *w, int n) {
priority_queue<struct node*, vector<struct node*>, cmp >q;
//初始化
for (int i = 0; i < n; i++) {
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data = *ch;
temp->weight = *w;
temp->left = temp->right = NULL;
q.push(temp);
ch++;
w++;
}
struct node* ans = NULL;
for(int i = 1; i<n; i++){
struct node *a = (struct node*)malloc(sizeof(struct node));
struct node *b = (struct node*)malloc(sizeof(struct node));
struct node *tmp = (struct node*)malloc(sizeof(struct node));
a = q.top();
q.pop();
b = q.top();
q.pop();
tmp->weight = a->weight + b->weight;
tmp->data = NULL;
tmp->left = a; //最小的作为左子树
tmp->right = b; //第二小的作为右子树
ans = tmp;
q.push(tmp);
}
cout << ans->weight << endl;
return ans;
}
void print(struct node* root, string res) {
if (!root)
return;
if (!root->left && !root->right && root->data) {
cout << root->data << ": ";
cout << res << endl;
}
print(root->left, res + "0");
print(root->right, res + "1");
}