poj3253

《挑战程序设计竞赛》练习

Posted by SHIELD-SKY on August 10, 2016

Fence Repair

Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs N (1 ≤ N ≤ 20,000) planks of wood, each having some integer length Li (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into the N planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the “kerf”, the extra length lost to sawdust when a sawcut is made; you should ignore it, too.

FJ sadly realizes that he doesn’t own a saw with which to cut the wood, so he mosies over to Farmer Don’s Farm with this long board and politely asks if he may borrow a saw.

Farmer Don, a closet capitalist, doesn’t lend FJ a saw but instead offers to charge Farmer John for each of the N-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.

Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create the N planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.

大体思路就是选最短的和次短的木板相加,递归的将剩下的N-1块木板的问题按相同思路求解 一种是类似构造最优二叉树的思路:

//贪心,O(N^2)解法
#include <iostream>
#include <algorithm>

using namespace std;

const int MAX_N = 60000;
typedef long long  ll;

int N, L[MAX_N];

void solve()
{
    ll ans = 0;
    while(N > 1)
    {
        int min1 = 0, min2 = 1;
        if (L[min1] > L[min2]) swap(min1, min2);
        
        for(int i = 2; i < N; i++)
            if (L[i] < L[min1]) {
                min2 = min1;
                min1 = i;
            }
            else if(L[i] < L[min2]) {
                min2 = i;
            }
        
        int t = L[min1] + L[min2];
        ans += t;
        
        if (min1 == N - 1) swap(min1, min2);
        L[min1] = t;
        L[min2] = L[N - 1];
        N--;
    }
    
    cout << ans << endl;
}

int main() {
    while(cin >> N){
        for(int i=0;i<N;i++)
            cin >> L[i];
        solve();
    }
    return 0;
}

一种是用优先队列实现

//O(NlogN)解法,使用优先队列
#include <iostream>
#include <queue>
#include <cstdio>

using namespace std;

typedef long long  ll;
const int MAX_N = 60000;

int N, L[MAX_N];

void solve()
{
    ll ans = 0;
    
    priority_queue<int, vector<int>, greater<int> > que;
    for(int i = 0; i < N; i++)
    {
        que.push(L[i]);
    }
    while (que.size() > 1) {
        int l1, l2;
        l1 = que.top();
        que.pop();
        l2 = que.top();
        que.pop();
        
        ans += l1 + l2;
        que.push(l1 + l2);
    }
    printf("%lld\n", ans);
}

int main() {
    while(cin >> N){
        for(int i=0;i<N;i++)
            cin >> L[i];
        solve();
    }
    return 0;
}