1. 程式人生 > >POJ 3252 Fence Repair

POJ 3252 Fence Repair

把一個木板切割成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;
}