头像

欢迎来到我的博客

分享题解与总结

哈夫曼编码(3)

P6033 合并果子 加强版

P6033 合并果子 加强版 - 洛谷

题意:

\(n\)堆果子\((1<=n<=10^7)\)合并成一堆,每堆果子初始\(1<=a_i<=10^5\)

求体力消耗最小值

思路:

如果初始的\(n\)堆果子是有序的

合并、维护单增性:可以用两个queue实现

二合一的新堆一定比原来重

如何让初始的果子有序?

鉴于\(1<=a_i<=10^5\),可以用桶排序 \(^{[1]}\)

代码:

const int N=1e5;
int tong[N+10];
queue<ll> q1,q2;

inline int read()
{
    int ans=0,neg=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-') neg*=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        ans=ans*10+ch-'0';
        ch=getchar();
    }
    return neg*ans;
}

ll getnum()
{
    ll ans=0;
    if(q1.empty()) {ans=q2.front();q2.pop();}
    else if(q2.empty()) {ans=q1.front();q1.pop();}
    else {
        if(q1.front()<q2.front()) {ans=q1.front(); q1.pop();}
        else {ans=q2.front(); q2.pop();}
    }
    return ans;
}

int main()
{
    int n; n=read();
    int a;
    
    for(int i=1;i<=n;++i){
        a=read(); tong[a]++;
    }
    for(int i=1;i<=N;++i){
        while(tong[i]--){
            q1.push(i);
        }
    }
    ll ans=0;
    while(q1.size()+q2.size()>1){
        ll first,second;
        first=getnum();
        second=getnum();
        ans+=first+second;
        q2.push(first+second);
    }
    cout<<ans;
    return 0;
}

\([1]\) 参考文献1

posted @ 2026-10-18 17:56  king_steph1209  阅读(9)  评论(0)    收藏  举报