AcWing:. 148 Merge fruit (Huffman)

In an orchard, Dada has shot down all the fruit, and different types of fruit into different piles.

Dada decided to put all the fruit of the synthetic pile.

Each combined, fruit piles People can merge together, equal to the weight of the physical consumption of fruit and two stacks.

As can be seen, all the fruits were combined after n-1 times, on the left a pile.

People When combined total fruit consumption combined physical strength is equal to the sum of each consumed.

But also because these fruits make great efforts to move back home, so when the fruit Dada merger to save energy as much as possible.

Number and the number of each type of fruit Fruit wt assumed that each are 1, and it is known fruit, your task is to design the combined sequence program to make physical People spend a minimum, and outputs the minimum value of the physical cost .

For example, three kinds of fruit, followed by the number 1,2,9.

1,2 stack may be first combined, the number of the new stack 3, 3 taxing.

Subsequently, the new stack and the third stack combined original, and to give the new stack number is 12, 12 is taxing.

Therefore, a total of taxing People = 3 + 12 = 15.

15 can be shown that the minimum value of the physical cost.

Input Format

Input consists of two lines, the first line is an integer n, the number of types of fruit.

The second line contains n integers, separated by spaces, the integer i A i AI is the number of i-th fruit.

Output Format

Including output line, which contains a single integer, i.e. the value of the minimum physical cost.

The input data to ensure that this value is less than 2 31 is 231

data range

1n100001≤n≤10000,
1ai200001≤ai≤20000

Sample input:

3 
1 2 9 

Sample output:

15

 

Algorithm: Small heap root

 

#include <iostream>
#include <cstdio>
#include <queue>
#include <functional>

using namespace std;

priority_queue<int, vector<int>, greater<int> > q;

int main() {
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        int x;
        scanf("%d", &x);
        q.push(x);
    }
    int ans = 0;
    while(q.size() > 1) {
        int first = q.top();
        q.pop();
        int second = q.top();
        q.pop();
        ans += first + second;
        q.push(first + second);
    }
    printf("%d\n", ans);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/buhuiflydepig/p/11330527.html