题解:P7840 「C.E.L.U-03」重构

· · 题解

话说这道题为什么我会卡了一个小时?

贪心

标签都告诉你贪心了,你不贪留着过年吗?

那么,怎么贪呢?

既然每个电缆的网速是 d_i^2 \cdot v_i,那么,当我 v_i 越大时,d_i 越小更优。

那么首先,我们需要给 v_i 排序,让 v_i 从小到大排序。

然后根据树的特性会发现,\sum d_i = 2n - 2,且每个点都至少有 v_i 的贡献,所以我们只需要最小化剩下的 n - 2 即可。

如何最小化?使用优先队列比较 ((x_{cnt} + 1) \times (x_{cnt} + 1) - x_{cnt} \times x_{cnt}) \times x_{num} <((y_{cnt} + 1) \times (y_{cnt} + 1) - y_{cnt} \times y_{cnt}) \times y_{num},其中 cnt 为使用次数,num 为 v_i。

为什么要怎么写?

因为我们每次的 d_i 都需要平方,若需要相加,加的值应为 now_{d_i} ^ 2 - last_{d_i} ^ 2,读者自证不难。

代码

#include<bits/stdc++.h>
using namespace std;
int v;
struct node{
    int cnt,num;
    bool operator <(const node&x) const{
        return ((x.cnt + 1) * (x.cnt + 1) - x.cnt * x.cnt) * x.num < ((cnt + 1) * (cnt + 1) - cnt * cnt) * num;
    }
};
priority_queue<node> q;
int main(){
    int n;
    cin >> n;
    int ans = 0;
    for(int i = 1;i <= n;i++){
        cin >> v;
        q.push((node){1,v});
        ans += v;
    }
    for(int i = 1;i <= n - 2;i++){
        int x = q.top().num,cnt = q.top().cnt;
        q.pop();
        ans += ((cnt + 1) *(cnt + 1) - cnt * cnt) * x;
        q.push((node){cnt + 1,x});
    }
    cout << ans << "\n";
    return 0;
}