1.解题思路
本题借鉴:浙大数据结构05-树9 Huffman Codes_哈夫曼树_shu.da-ho9-CSDN博客
2.代码
#include <bits/stdc++.h>
using namespace std;
priority_queue<int,vector<int>,greater<int>> q;
unordered_map<char,int> un_map;
int n,m,wpl=0;
int cmp(string&a,string&b){
return a.size()<b.size();
}
//判断是否为前缀
int isPrefix(string code[]){
sort(code,code+n,cmp);
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(code[j].substr(0,code[i].size())==code[i]){
return 1;
}
}
}
return 0;
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
char ch;
int frequency;
cin>>ch;
cin>>frequency;
un_map[ch]=frequency;
q.push(frequency);
}
while(q.size()>1){
int x=q.top();
q.pop();
int y=q.top();
q.pop();
q.push(x+y);
wpl+=x+y;
}
cin>>m;
while(m--){
int res=0;
char ch;
string code[64];
for(int i=0;i<n;i++){
cin>>ch;
cin>>code[i];
res += code[i].size()*un_map[ch];
}
if(res!=wpl||isPrefix(code)){
if(m!=0){
cout<<"No"<<endl;
}
else{
cout<<"No";
}
}
else{
if(m!=0){
cout<<"Yes"<<endl;
}
else{
cout<<"Yes";
}
}
}
return 0;
}
3.WPL计算解释
计算WPL时,主要根据一个所有非叶节点相加即为WPL值。
如图,该树的WPL = 2A + 2B + D
又因为 C = A + B,E = C + D = A + B + D
所以 C+E = 2A + 2B + D = WPL