【洛谷P2168】[NOI2015]荷马史诗

荷马史诗

建一个k叉哈夫曼树,用堆维护一下

 1 // luogu-judger-enable-o2
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<queue>
 6 using namespace std;
 7 #define MAXN 1000010
 8 #define max(i,j) ((i)>(j)?(i):(j))
 9 #define int long long
10 int n,ans,k;
11 struct NODE{
12     int w,h;
13 } a[MAXN];
14 struct cmp{
15     bool operator()(NODE x,NODE y){ 
16         if(x.w!=y.w) return x.w>y.w;  // 先按代价大小排序
17         else return x.h>y.h;      // 再按子树深度排序
18     }
19 };
20 inline int read(){
21     int x=0; char c=getchar();
22     while(c<'0'||c>'9') c=getchar();
23     while('0'<=c&&c<='9') { x=(x<<3)+(x<<1)+c-'0'; c=getchar(); }
24     return x;
25 }
26 priority_queue< NODE, vector < NODE > , cmp > q0,q;
27 #undef int
28 int main()
29 #define int long long
30 {
31     n=read(); k=read();
32     int x; NODE p0;
33     p0.w=0; p0.h=1;
34     for(int i=1;i<=n;i++){
35         x=read(); NODE p;
36         p.w=x; p.h=1; q0.push(p);
37     }
38     q=q0; ans=0;
39     int top=0;
40     if((n-1)%(k-1)!=0) top=k-1-(n-1)%(k-1);
41     for(int i=1;i<=top;i++) q.push(p0);
42     while(q.size()>1){
43         NODE s=p0;
44         for(int i=1;i<=k;i++){
45             NODE b=q.top(); q.pop();
46             ans+=b.w; s.w+=b.w; s.h=max(s.h,b.h);
47         }
48         s.h++;
49         q.push(s);
50     }
51     NODE t=q.top();
52     printf("%lld\n%lld",ans,t.h-1);
53     return 0;
54 }

 

posted @ 2018-06-20 21:20  yjk  阅读(204)  评论(0编辑  收藏  举报