Fence Repair--POJ3253

[C++]Fence Repair(贪心)

Fence Repair:
农夫约翰为了修理栅栏,要将一块很长的木板切割成N块。准备切成的木块的长度为L1, L2,…Ln,未切割前木板的长度恰好为切割后木板长度的总和。每次切割木板时,需要的开销为这块木板的长度。例如长度为21的木板要切成长度为5,8,8的三块木板。长21的木板切成长为13和8的木板时,开销为21.再将长度为13的板切成长度为5和8的板时,开销为13.于是合计开销时34.请求出按照目标要求将木板切割完最小的开销是多少。
输入格式:
Line 1: One integer N, the number of planks
Lines 2… N+1: Each line contains a single integer describing the length of a needed plank
输出格式:
Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts

输入:
3
8 5 8
输出:
34

解题思路:每次选择最小的两块木板相加,并将结果加入待选择木板列中,直到只剩下一块木板为止。

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

typedef long long ll;

const int maxn = 20000 + 10;

int n;
ll L[maxn];

int main(){
    cin>>n;
    
    for(int i = 0; i<n; i++){
        cin>>L[i];
    }
    sort(L, L+n);
    ll sum = 0;
    while(n > 1){
        int m1 = 0, m2 = 1;
        if(L[m1] > L[m2]){
            int t = m1;
            m1 = m2;
            m2 = t;
        }   
        for(int i = 2; i<n; i++){
            if(L[i] < L[m1]){
                m2 = m1;
                m1 = i;
            } 
            else if(L[i] < L[m2]){
                m2 = i;
            }
        }
        ll res = L[m2] + L[m1];
        sum += res;
        if(m1 == n-1){
            int t = m1;
            m1 = m2;
            m2 = t;
        }
        L[m1] = res;
        L[m2] = L[n-1];
        n--;
    }
    
    cout<<sum<<endl;
    
    return 0;
}
发布了63 篇原创文章 · 获赞 8 · 访问量 7198

猜你喜欢

转载自blog.csdn.net/s1547156325/article/details/104393222