7-10 Repair Ranch

                                                                      7-10 Repair Ranch (25 points)

The farmer wants to repair a section of the fence on the ranch. He measured the fence and found that N pieces of wood are needed. The length of each piece of wood is an integer Li​​​​​​ , That is, the length of the wood is the sum of Li​​.

But the farmer himself does not have a saw, and the reward for asking someone to saw the wood is proportional to the length of the wood. For the sake of simplicity, set the reward equal to the length of the sawn wood. For example, to saw a length of 20 wood into three segments with lengths 8, 7, and 5. The first time sawing the wood costs 20, and the wood is sawing 12 and 8; the second time sawing the wood costs 12, and the length is 12 Wood sawn into 7 and 5, the total cost is 32. If the wood is sawed into 15 and 5 for the first time, the second sawing will cost 15 and the total cost will be 35 (more than 32).

Please write a program to help the farmer calculate the minimum cost of sawing wood into N pieces.

Input format:

The input first gives a positive integer N (≤ 10^{4}), which means that the wood is to be sawn into N pieces. The second line gives N positive integers (≤50), indicating the length of each piece of wood.

Output format:

Output an integer, the minimum cost of sawing wood into N pieces.

Input sample:

8
4 5 1 2 1 3 1 1

Sample output:

49

Problem-solving idea: Every time you choose the shortest two pieces of wood in the ordered queue to form a piece of wood, and then insert the new wood into the ordered queue, it can cost the least. With the help of multiset tools.

#include <bits/stdc++.h>
using namespace  std;
multiset<int>mset;
int main()
{
    int n;
    scanf("%d",&n);
    while (n--){
        int x;scanf("%d",&x);
        mset.insert(x);
    }
    if(mset.size()==1){printf("0\n");return 0;}
    int sum=0,x,y;
    while(mset.size()>2){
        x = *mset.begin();mset.erase(mset.begin());
        y = *mset.begin();mset.erase(mset.begin());
        sum = sum + x+y;mset.insert(x+y);
    }
    while(!mset.empty()){
        sum = sum + *mset.begin();
        mset.erase(mset.begin());
    }
    printf("%d\n",sum);
    return 0;
}

 

Guess you like

Origin blog.csdn.net/zw201909250425/article/details/105762282