Data Structures and Algorithms (English) - 7-9 Huffman Codes(30 分)

简介: Data Structures and Algorithms (English) - 7-9 Huffman Codes(30 分)

题目链接点击打开链接

题目大意:验证是否为哈夫曼树。

解题思路:验证哈夫曼树的两个必要条件:

  1. 非叶子节点Weight之和 == WPL == Li*Wi + ..之和。
  2. 任何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 1000000007usingnamespacestd;
typedeflonglongll;
structnode{
intw;
strings;
}nds[70];
priority_queue<int,vector<int>,greater<int>>pq;
unordered_map<char,int>ump;
intn;
boolok()
{
for(inti=0;i<n;i++)
    {
stringpre=nds[i].s;
for(intj=0;j<n;j++)
        {
if(i!=j&&pre==nds[j].s.substr(0,pre.length()))
returnfalse;
        }
    }
returntrue;
}
intmain()
{
intm,wpl=0;
charc;
scanf("%d ",&n);
for(inti=0;i<n;i++)
    {
scanf("%c",&c);
scanf("%d ",&ump[c]);
pq.push(ump[c]);
    }
while(1)
    {
inttp=pq.top(); pq.pop();
if(pq.empty()) break;
tp+=pq.top(); pq.pop();
pq.push(tp);
wpl+=tp;
    }
scanf("%d",&m);
while(m--)
    {
intsum=0;
for(inti=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");
elseputs("No");
    }
return0;
}
目录
相关文章
|
存储 容器
Data Structures and Algorithms (English) - 7-18 Hashing - Hard Version(30 分)
Data Structures and Algorithms (English) - 7-18 Hashing - Hard Version(30 分)
222 0
Data Structures and Algorithms (English) - 7-18 Hashing - Hard Version(30 分)
|
机器学习/深度学习 算法
Data Structures and Algorithms (English) - 7-28 Review of Programming Contest Rules(30 分)
Data Structures and Algorithms (English) - 7-28 Review of Programming Contest Rules(30 分)
216 0
Data Structures and Algorithms (English) - 7-28 Review of Programming Contest Rules(30 分)
Data Structures and Algorithms (English) - 6-15 Iterative Mergesort(25 分)
Data Structures and Algorithms (English) - 6-15 Iterative Mergesort(25 分)
193 0
Data Structures and Algorithms (English) - 6-8 Percolate Up and Down(20 分)
Data Structures and Algorithms (English) - 6-8 Percolate Up and Down(20 分)
105 0
Data Structures and Algorithms (English) - 6-17 Shortest Path [4](25 分)
Data Structures and Algorithms (English) - 6-17 Shortest Path [4](25 分)
116 0
Data Structures and Algorithms (English) - 6-16 Shortest Path [3](25 分)
Data Structures and Algorithms (English) - 6-16 Shortest Path [3](25 分)
106 0
Data Structures and Algorithms (English) - 6-11 Shortest Path [2](25 分)
Data Structures and Algorithms (English) - 6-11 Shortest Path [2](25 分)
128 0
Data Structures and Algorithms (English) - 6-11 Shortest Path [1](25 分)
Data Structures and Algorithms (English) - 6-11 Shortest Path [1](25 分)
117 0
Data Structures and Algorithms (English) - 6-1 Deque(25 分)
Data Structures and Algorithms (English) - 6-1 Deque(25 分)
102 0
Data Structures and Algorithms (English) - 6-13 Topological Sort(25 分)
Data Structures and Algorithms (English) - 6-13 Topological Sort(25 分)
112 0

热门文章

最新文章