话说这道题为什么我会卡了一个小时?
贪心
标签都告诉你贪心了,你不贪留着过年吗?
那么,怎么贪呢?
既然每个电缆的网速是 ,那么,当我 越大时, 越小更优。
那么首先,我们需要给 排序,让 从小到大排序。
然后根据树的特性会发现,,且每个点都至少有 的贡献,所以我们只需要最小化剩下的 即可。
如何最小化?使用优先队列比较 ,其中 为使用次数, 为 。
为什么要怎么写?
因为我们每次的 都需要平方,若需要相加,加的值应为 ,读者自证不难。
代码
#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;
}