Loading

CF844D Boxes And Balls

题意

\(n\) 个箱子、\(n\) 种颜色的球,第 \(i\) 种颜色的球有 \(w_i\) 个,最开始时都在第 \(1\) 个箱子中。

每次可以从有球的一个箱子中拿出所有球,并随意分割为 2 部分或 3 部分,并放入箱子,需要的代价为球的总数。

问将每种颜色的球都放在对应的一个箱子中需要的代价最少是多少。

思路

我们把拆分的过程倒过来想,这个过程就像哈夫曼树的合并操作。

如果优先队列中有 3 个元素,必定选择 3 个数字进行合并,但是为了避免讨论,我们可以人为加入元素个数达到每次合并都有 3 个颜色的目的。

加入元素的过程参考我的博客:P2168 [NOI2015] 荷马史诗

代码

#include <bits/stdc++.h>

using namespace std;
using i64 = long long;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    priority_queue<i64, vector<i64>, greater<i64> > q;

    cin >> n;
    for (int i = 1; i <= n; i++) {
        int x;
        cin >> x;
        q.push(x);
    }

    while (n % 2 != 1) {
        n++;
        q.push(0);
    }

    i64 ans = 0;
    while (q.size() > 1) {
        i64 sum = 0;
        for (int i = 1; i <= 3; i++) {
            i64 x = q.top();
            q.pop();
            sum += x;
        }
        ans += sum;
        q.push(sum);
    }
    cout << ans << '\n';
    return 0;
}
posted @ 2024-08-10 13:19  SunnyYuan  阅读(3)  评论(0编辑  收藏  举报