problem
- 有n堆果子
- 每次可以将两堆果子合并,代价为新堆的果子数。
- 求把所有果子合并成一堆的最小代价。
solution
- 每次合并最小的两堆
- 用堆或者两个队列维护
证明?反证法。
codes
#include<iostream>
#include<queue>
using namespace std;
priority_queue<int, vector<int>, greater<int> >q;
int main(){
int n, ans = 0; cin>>n;
for(int i = 0; i < n; i++){
int a; cin>>a; q.push(a);
}
for(int i = 0; i < n-1; i++){
int a = q.top(); q.pop();
int b = q.top(); q.pop();
ans += a+b; q.push(a+b);
}
cout<<ans;
return 0;
}