求WPL的代码(不用建树),给定n个叶子节点。
时间复杂度 \(O(n\log n)\)
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define rint register int #define il inline inline int rd(){ int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar(); return x*f; } struct node { int val,h; friend bool operator < (node a,node b) { return a.val!=b.val?a.val>b.val:a.h>b.h; } }; priority_queue<node>q; const int N=505; int n,ans; int main() { n=rd(); for(rint i=1;i<=n;++i) q.push(node{rd(),1}); for(rint i=1;i<n;++i) { int tmp=0,mx=0; tmp+=q.top().val;mx=max(mx,q.top().h);q.pop(); tmp+=q.top().val;mx=max(mx,q.top().h);q.pop(); ans+=tmp;q.push(node{tmp,mx+1}); } printf("%d\n",ans); return 0; }
第1个值就是WPL,第2个值就是哈夫曼树的深度。其余就是板子。
#include<bits/stdc++.h> using namespace std; #define int long long #define rint register int #define il inline inline int rd(){ int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar(); return x*f; } struct node { int val,h; friend bool operator < (node a,node b) { return a.val!=b.val?a.val>b.val:a.h>b.h; } }; priority_queue<node>q; const int N=1e5+10; int n,k,ans,sum,dep,tmp,mx; signed main() { n=rd(),k=rd(); for(rint i=1;i<=n;++i) q.push(node{rd(),1}); if((n-1)%(k-1))sum=k-1-(n-1)%(k-1); for(rint i=1;i<=sum;++i) q.push(node{0,0}); n=(n+sum-1)/(k-1); for(rint i=1;i<=n;++i){ tmp=0,mx=0; for(rint j=1;j<=k;++j) tmp+=q.top().val,mx=max(mx,q.top().h),q.pop(); ans+=tmp;dep=max(dep,mx); q.push(node{tmp,mx+1}); } printf("%lld\n%lld\n",ans,dep); return 0; }
来源:https://www.cnblogs.com/zzctommy/p/12403493.html