[NOI2015] Homer Epic

Keywords: Python

Luo Gu

BZOJ

Meaning: there are n different words in a Homer epic, numbered from 1 to n. The total number of occurrences of the first word is wi. Allison wants to replace the ith word with the k-ary string si to meet the following requirements: for any 1 ≤ i, j ≤ n, i ≠ j, si is not the prefix of sj. Now Allison wants to know how to choose si to minimize the length of the new Homer epic. Allison also wants to know what is the shortest length of the longest si when ensuring the minimum total length? A string is called a k-ary string if and only if each of its characters is an integer between 0 and K − 1, inclusive.

Analysis: the first question is the template problem of Huffman tree. In the second question, as long as the nodes with the same weight value are used to find the Huffman tree, the nodes with the lowest current depth should be combined first. Specifically, when sorting the overloaded operators, it should be written as \ (Val = = x.val? Deep > x.deep: Val > x.val \) instead of simple \ (Val > x.val \);

//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#define LL long long
using namespace std;
inline LL read(){
    LL x=0,o=1;char ch=getchar();
    while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
    if(ch=='-')o=-1,ch=getchar();
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x*o;
}
struct node{
    LL val,deep;
    bool operator <(const node &x)const{
        return val==x.val?deep>x.deep:val>x.val;
    }
}temp;
priority_queue<node>q;
inline void Huffman(LL n,LL k){
    LL ans=0;
    while(n>1){
        LL max_deep=0,tot=0;
        for(LL i=1;i<=k;++i){
            temp=q.top();q.pop();
            tot+=temp.val;max_deep=max(max_deep,temp.deep);
        }
        temp.val=tot;temp.deep=max_deep+1;q.push(temp);
        ans+=tot;n-=k-1;
    }
    printf("%lld\n%lld\n",ans,q.top().deep-1);
}
int main(){
    LL n=read(),k=read();
    for(LL i=1;i<=n;++i){
        LL v=read();
        temp.val=v;temp.deep=1;q.push(temp);
    }
    LL res=(n-1)%(k-1);
    if(res!=0)res=k-1-res,n+=res;
    for(LL i=1;i<=res;++i)temp.val=0,temp.deep=1,q.push(temp);
    Huffman(n,k);
    return 0;
}

Posted by haddydaddy on Tue, 15 Oct 2019 08:24:20 -0700