题目链接:点击打开链接
题目大意:验证是否为哈夫曼树。
解题思路:验证哈夫曼树的两个必要条件:
- 非叶子节点Weight之和 == WPL == Li*Wi + ..之和。
- 任何01字符串都不是其他字符串的前缀。
AC 代码
#include<bits/stdc++.h>
#include<cmath>
#define mem(a,b) memset(a,b,sizeof a)
#define ssclr(ss) ss.clear(), ss.str("")
#define INF 0x3f3f3f3f
#define MOD 1000000007
using namespace std;
typedef long long ll;
struct node
{
int w;
string s;
}nds[70];
priority_queue<int,vector<int>,greater<int>> pq;
unordered_map<char,int> ump;
int n;
bool ok()
{
for(int i=0;i<n;i++)
{
string pre=nds[i].s;
for(int j=0;j<n;j++)
{
if(i!=j && pre==nds[j].s.substr(0,pre.length()))
return false;
}
}
return true;
}
int main()
{
int m,wpl=0;
char c;
scanf("%d ",&n);
for(int i=0;i<n;i++)
{
scanf("%c",&c);
scanf("%d ",&ump[c]);
pq.push(ump[c]);
}
while(1)
{
int tp=pq.top(); pq.pop();
if(pq.empty()) break;
tp+=pq.top(); pq.pop();
pq.push(tp);
wpl+=tp;
}
scanf("%d",&m);
while(m--)
{
int sum=0;
for(int i=0;i<n;i++)
{
scanf(" %c",&c);
cin>>nds[i].s;
nds[i].w=ump[c];
sum+=nds[i].w*nds[i].s.length();
}
if(sum==wpl && ok()) puts("Yes");
else puts("No");
}
return 0;
}