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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值