poj 3253 Fence Repair【优先队列,堆】

大致题意:

有一个农夫要把一个木板钜成几块给定长度的小木板,每次锯都要收取一定费用,这个费用就是当前锯的这个木版的长度

给定各个要求的小木板的长度,及小木板的个数n,求最小费用

以3 8 5 8为例,一共3个木板,长为8 5 8,先取5 8,为13,在取8 13,为21,两次取的和为34.

STL优先队列:

Memory: 1000K   Time: 32MS
Language: G++   Result: Accepted
View Code
#include<stdio.h>
#include<queue>
using namespace std;

#define llong long long

priority_queue<llong, vector<llong>, greater<llong> > Q;

int main()
{
    int n;
    while(scanf("%d", &n) != EOF) {
        while( !Q.empty() ) Q.pop();
        for(int i = 0; i < n; i++) {
            int m;
            scanf("%d", &m);
            Q.push(m);
        }
        llong tot = 0;
        while( !Q.empty() ) {
            llong k;
            k = Q.top();
            Q.pop();
            k += Q.top();
            Q.pop();
            tot += k;
            if( !Q.empty() ) Q.push(k);
        }
        printf("%lld\n", tot);
    }
    return 0;
}

STL 堆:

Memory: 516K   Time: 16MS
Language: G++   Result: Accepted
View Code
#include<stdio.h>
#include<algorithm>
using namespace std;

#define llong long long

llong arr[200001];

bool cmp(llong a, llong b)
{
    return a > b;
}

int main()
{
    int n;
    while(scanf("%d", &n) != EOF) {
        for(int i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }
        make_heap(arr, arr+n, cmp);
        llong tot = 0;
        while(1) {
            llong t = arr[0];
            pop_heap(arr, arr+n,cmp);
            n--;
            t += arr[0];
            pop_heap(arr, arr+n, cmp);
            n--;
            tot += t;
            if( !n ) break;
            arr[n] = t;
            n++;
            push_heap(arr, arr+n, cmp);
        }
        printf("%lld\n", tot);
    }
    return 0;
}

 本题测试数据:http://ace.delos.com/TESTDATA/NOV06_4.htm

posted @ 2012-07-31 14:49  小猴子、  阅读(328)  评论(0编辑  收藏  举报