#C6212. Minimize Sum of Conflicts
Minimize Sum of Conflicts
Minimize Sum of Conflicts
Given n students with various heights, arrange them in a line such that the sum of conflicts between every two adjacent students is minimized. The conflict between two adjacent students is defined as the absolute difference of their heights. It can be shown that sorting the heights in non-decreasing order minimizes the total conflict.
The problem is formulated mathematically as follows:
Let \(h_1, h_2, \ldots, h_n\) be the heights of the students. We need to find a permutation of the heights that minimizes
[ S = \sum_{i=1}^{n-1} |h_{p(i)} - h_{p(i+1)}| ]
Show that when the list is sorted, i.e. \(h_{(1)} \le h_{(2)} \le \ldots \le h_{(n)}\), then the minimal sum is:
[ S_{min} = \sum_{i=1}^{n-1} \left(h_{(i+1)} - h_{(i)}\right) ]
Your task is to implement this logic by reading input from standard input and output the result to standard output.
inputFormat
The first line contains an integer n, the number of students.
The second line contains n space-separated integers representing the heights of the students.
outputFormat
Output a single integer, which is the minimum sum of conflicts after arranging the students optimally.
## sample5
1 5 3 2 4
4
</p>