Huffman Tree
If you want the maximum depth to be the smallest, then you can sort by H.
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>#defineMAXV 100500#defineMaxe 1000500using namespacestd;Long Longn,k,val[maxv*5],nume=0, g[maxv*5],tot,sum=0, dis[maxv*5],fath[maxv*5];structedge{Long LongV,NXT;} E[maxe];structstatus{Long Longval,pnt,h;};BOOL operator<(status X,status y) {if(X.val!=y.val)returnX.val>Y.val; returnX.h>Y.h;} Priority_queue<status>Q;voidAddedge (Long LongULong Longv) {e[++nume].v=v; E[NUME].NXT=G[u]; G[u]=Nume;}voidDfsLong Longx) { for(Long LongI=g[x];i;i=e[i].nxt) { Long Longv=e[i].v; if(v!=Fath[x]) {Fath[v]=x;dis[v]=dis[x]+1; DFS (v); } }}intMaxintAintb) { if(A>B)returnA; returnb;}intMain () {scanf ("%lld%lld",&n,&k); for(Long LongI=1; i<=n;i++) {scanf ("%lld",&Val[i]); Status S; S.PNT=i;s.val=val[i];s.h=0; Q.push (s); } Long Longret=0; while((n+ret-1)% (K-1)!=0) ret++; for(Long LongI=1; i<=ret;i++) {status S; S.PNT=n+i;s.val=0; s.h=0; Q.push (s); Val[n+i]=0; } N+=ret;tot=N; Long Longret1=0, ret2=0; while(Q.size () >1) {sum=0; tot++;intmx=0; for(Long LongI=1; i<=k;i++) {Status B=q.top (); Q.pop (); Sum+=b.val;mx=Max (mx,b.h); Addedge (B.pnt,tot); Addedge (TOT,B.PNT); } status S; S.PNT=tot;s.val=sum;s.h=mx+1; Q.push (s); Ret2=Max (ret2,s.h); Val[tot]=0; } dfs (TOT); for(Long LongI=1; i<=n;i++) Ret1+=val[i]*Dis[i]; printf ("%lld\n%lld\n", Ret1,ret2); return 0;}
Bzoj 4198 Homer Epic