Problem Description
Huffman trees are widely used in coding. Here, we only care about the construction process of the Huffman tree.
Given a list of numbers { pi }={ p 0, p 1, …, pn -1}, the process of constructing a Huffman tree with this list of numbers is as follows: 1. Find the two smallest numbers in { pi } and set them as pa and pb , delete pa and pb from { pi }, and then add their sum to { pi }. The cost of this process is recorded as pa + pb . 2. Repeat step 1 until there is only one number left in { pi }. In the above operation process, all the costs are added together to get the total cost of constructing the Huffman tree. Task of this question: For a given sequence, now please find the total cost of constructing a Huffman tree with the sequence. For example, for the sequence { pi }={5, 3, 8, 2, 9}, the construction process of the Huffman tree is as follows:
1. Find the two smallest numbers in {5, 3, 8, 2, 9}, which are 2 and 3, delete them from { pi } and add the sum 5 to {5, 8, 9, 5} , The cost is 5. 2. Find the two smallest numbers in {5, 8, 9, 5}, 5 and 5, delete them from { pi } and add the sum 10 to {8, 9, 10}, cost 10 . 3. Find the two smallest numbers in {8, 9, 10}, which are 8 and 9, delete them from { pi } and add the sum 17 to {10, 17}, and the cost is 17. 4. Find the two smallest numbers in {10, 17}, namely 10 and 17, delete them from { pi } and add the sum 27 to get {27}, the cost is 27. 5. Now, there is only one number 27 left in the sequence. The construction process is over, and the total cost is 5+10+17+27=59.
Input format
The first line of input contains a positive integer n ( n <=100).
Next are n positive integers, representing p 0, p 1, …, pn -1, and each number does not exceed 1000.Output format
Output the total cost of constructing the Huffman tree with these numbers.
Sample input
5
5 3 8 2 9Sample output
59
Diagram of my thinking :
(Look with the code)
Each time the order is sorted, the sum of the two smallest numbers is updated to the second of the two numbers added.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[110],b[1010],n,i,j;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);//输入
int sum=0,k=0;
while(k!=n-1)
{
sort(a,a+n);
sum+=a[k]+a[k+1];
a[k+1]=a[k+1]+a[k];
k++;
}
printf("%d",sum);
return 0;
}
This question suggests to write with greed, but this scum is greedy and doesn't know how to write it, embarrassing.
So I wrote it in my own way of thinking, but I never thought of it.