把一个木板切割成N块,每次切割的花费是原木板的长度。N块木板的长度给出,求最小花费。
这个题需要反过来看。最小和次小的两块木板是最后被切的。。每次都把最小和次小取出,加入ans,然后把两者相加放入堆中。
需要注意的是数据的大小用long long, 因为STL默认大根堆,在把数据插入堆中的时候*-1就是小根堆了。
#include<cstdio>
#include<queue>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
int n;
LL ans;
priority_queue<LL> a;
int main(){
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
a.push((LL)x * (-1));
}
while(a.size() > 1){
LL x = a.top() * (-1);
a.pop();
LL y = a.top() * (-1);
a.pop();
ans = ans + x + y;
a.push((x + y) * (-1));
}
printf("%lld", ans);
return 0;
}