9 degrees OJ-1107-moving fruit
Description:
In an orchard, James has already knocked down all the fruits and divided them into several heaps based on different types of fruits. James decided to combine all the fruits into a pile. For each merge, James can combine two piles of fruits, and the physical strength consumed is equal to the sum of the weights of the two piles of fruits. Of course, after n-1 merge, it will become a pile. The total physical strength consumed by James in merging fruits is the sum of the physical strength consumed by each merge.
Assuming that each fruit has a weight of 1 and the number of known fruit types and the number of each fruit, your task is to design a combined sequence scheme to minimize Xiao Ming's physical strength, and output the minimum physical labor consumption value. For example, there are three types of fruits, with numbers 1, 2, and 9 in sequence. You can merge 1 or 2 heaps. The number of new heaps is 3, and the physical strength is 3. Then combine the new heap with the original third heap to get the new heap, which consumes 12 resources. Therefore, James spent a total of 3 + 12 = 15, which can prove that 15 is the minimum physical labor cost.
Input:
Each data input includes two rows. The first row is an integer n (1 <= n <= 10000), indicating the number of fruit types. If n is equal to 0, the input ends, and does not need to be processed. The second line contains n integers separated by spaces. the I-th INTEGER (1 <= ai <= 1000) is the number of I-th fruits.
Output:
For each input group, an integer is output and a line break is generated. This value is the minimum physical labor consumption value. The input data must be less than 2 ^ 31.
Sample input:
3
9 1 2
0
Sample output:
15
This topic is essentially the sum of the nodes in the Huffman tree. The Huffman tree still imitates word2vec.
# Include
# Include
# Include
# Define MAX 2147483647 // 2 ^ 31-1int n; int * array; int min1, min2; // minimum and secondary small values pointer int pos1, pos2; // scan pointer int a; int cmp (const void * a, const void * B) {return * (int *) B-* (int *) ;} int main () {freopen ("input.txt", "r", stdin); while (scanf ("% d", & n )! = EOF & n) {array = (int *) malloc (2 * N-1) * sizeof (int); for (int I = 0; I <n; ++ I) scanf ("% d", array + I); for (int I = n; I <2 * n-1; ++ I) array [I] = MAX; qsort (array, n, sizeof (int), cmp); // for (int I = 0; I <2 * n-1; ++ I) printf ("% d ", array [I]); pos1 = n-1; pos2 = n; for (a = 0; a <n-1; ++ a) {if (pos1> = 0) // find min1 {if (array [pos1] = 0) // find min2 {if (array [pos1]