avatar
fireworks99
keep hungry keep foolish

POJ Fence Repair

Description

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.

Input

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

Output

Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts

Sample Input

3

8 5 8

Sample Output

34

题目大意

一块木板切成N块,每次开销是当前木板长度,给出最终每块木板长度,求最小开销

详见《挑战程序设计》(第二版)48页

自己举几个简单的例子发现:将 最短板次短板 视为来自同一块板,合成新板重复此过程便得到答案

关键处

为了找最短板与次短板,避免多次sort,采用vector的lower_bound式insert

vec.insert(lower_bound(vec.begin(), vec.end(), tem), tem);

code

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

int main()
{
    vector<int> vec;
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; ++i)
    {
        int tem;
        scanf("%d", &tem);
        vec.insert(lower_bound(vec.begin(), vec.end(), tem), tem);///vector据大小插入
    }
    long long ans = 0;/// >= 2个int可能超int
    while(vec.size() > 1)
    {
        int t = vec[0] + vec[1];
        ans += t;
        vec.erase(vec.begin());
        vec.erase(vec.begin());
        vec.insert(lower_bound(vec.begin(), vec.end(), t), t);
    }
    cout << ans << '\n';
    return 0;
}
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy