最优二叉树
哈夫曼树
定义
哈夫曼(Huffman)树又称最优二叉树或最优搜索树,是一种带权路径长度最短的二叉树。
构造方法
1.从所有节点中选两权值最小节点,将它们移除序列;
2.将一个新的结点放进序列,权值为上文两点权值之和;
3.若有必要,将新点与旧点之间建边;
4.重复1、2、3操作,直到只有一个节点。
性质
哈夫曼树的结点的度数为0或2,没有度为1的结点。
前置知识——重载运算符
P1090 [NOIP 2004 提高组] 合并果子
#include<bits/stdc++.h>
using namespace std;
#define int long long
struct Node{
int val;
bool operator < (const Node &x) const{
return x.val<val;
}
};
priority_queue<Node> q;
int n;
int a[10005];
int ans;
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
q.push((Node){a[i]});
}
for(int i=1;i<=n-1;i++){
Node x=q.top();
q.pop();
Node y=q.top();
q.pop();
ans+=x.val+y.val;
q.push((Node){x.val+y.val});
}
cout<<ans;
return 0;
}
P2168 [NOI2015] 荷马史诗
关键
实现最大深度最小需要在结构体中考虑在权值相等的情况下,深度小的优先。
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,k,len,op,sum1,maxx,ans;
int ave;
struct node{
int h,val;
bool operator < (const node &x) const {
if(x.val==val){
return x.h<h;
}
return x.val<val;
}
};
struct abc{
int val;
string s;
}a[400005];
priority_queue<node> q;
struct Node{
int to,w,nxt;
}e[400005];
int head[400005],tot;
signed main(){
cin>>n>>k;
len=n;
for(int i=1;i<=n;i++){
int x;
cin>>x;
a[i].val=x;
sum1+=x;
q.push({1,x});
}
while(n<k||(n-1)%(k-1)!=0){
n++;
q.push({1,0});
}
int poi=n;
for(int i=1;i<=(n-1)/(k-1);i++){
poi++;
int sum=0,maxx=0;
for(int j=0;j<k;j++){
node r=q.top();
q.pop();
maxx=max(maxx,r.h);
sum+=r.val;
}
ans+=sum;
q.push({maxx+1,sum});
}
cout<<ans<<endl<<q.top().h-1;
return 0;
}
UVA12676 Inverting Huffman
估计是绿,毕竟我太菜,大概率独立做不出蓝题……
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n;
struct node{
int ceng,val;
bool operator < (const node &x) const {
return x.ceng>ceng;
}
};
priority_queue<node> q;
signed main(){
while(cin>>n){
int la=1,ans=0;
for(int i=1;i<=n;i++){
int x;
cin>>x;
q.push({x,-1});
}
while(!q.empty()){
int sum=0,val=-1,a[50]={0},tot=0;
int ceng=q.top().ceng;
if(ceng==0){
q.pop();
break;
}
val=max(val,q.top().val);
a[++tot]=q.top().val;
sum+=(q.top().val==-1);
q.pop();
while(!q.empty()&&q.top().ceng==ceng){
val=max(val,q.top().val);
a[++tot]=q.top().val;
sum+=(q.top().val==-1);
q.pop();
}
for(int i=1;i<=tot;i++){
if(a[i]==-1){
a[i]=la;
}
}
sort(a+1,a+tot+1);
for(int i=1;i<=tot;i+=2){
q.push({ceng-1,a[i]+a[i+1]});
}
ans+=sum*la;
la=max((long long)1,val);
}
cout<<ans<<endl;
}
return 0;
}
课后甜点:UVA240 Variable Radix Huffman Encoding
样例过了,怎么也调不出来了……