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;
}
發佈了45 篇原創文章 · 獲贊 6 · 訪問量 4867
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章