翻了翻网上的题解,大多模拟了整棵Huffman树的构建过程
现给出不建树的方法
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct node{
string s;
int f;
node(string s, int f) {
this->s = s;
this->f = f;
}
};
bool cmp(node n1, node n2) {
return n1.f < n2.f;
}
vector<node> v;
map<char, int> mp, w;
int main(int argc, char** argv) {
int n;
scanf("%d", &n);
for(int i = 0;i < n; i++) {
string s;int f;
cin >> s >> f;
w[s[0]] = f;
v.push_back(node(s, f));
}
while(v.size() > 1) {//模拟Huffman建树过程,选出权值最小的两个结点进行合并(由于排序,即vector内第一个和第二个结点),并使被合并结点涉及的字符编码长度+1
sort(v.begin(), v.end(), cmp);
node n1 = v[0], n2 = v[1];
v.erase(v.begin()); v.erase(v.begin());
node n(n1.s+n2.s, n1.f+n2