#C5835. Minimize Sweetness Differences
Minimize Sweetness Differences
Minimize Sweetness Differences
You are given several cakes. Each cake consists of several layers, each with a given sweetness factor. For each cake, the first number indicates the number of layers, followed by the sweetness values of each layer. Your task is to rearrange the layers such that the sum of the absolute differences of sweetness between consecutive layers is minimized.
In other words, if a cake has layers with sweetness values arranged in the order \(a_1, a_2, \dots, a_m\), you need to reorder the layers so that the quantity \[ \sum_{i=1}^{m-1} \left|a_{i+1} - a_i\right| \] is minimized. A useful observation is that sorting the layers in non-decreasing order minimizes the sum of absolute differences.
Print the minimized sum for each cake.
inputFormat
The input is read from standard input (stdin) and has the following format:
T m1 a11 a12 ... a1m1 m2 a21 a22 ... a2m2 ... mt at1 at2 ... atmt
Where:
- T is the number of cakes.
- For each cake, the first integer m represents the number of layers, followed by m integers representing the sweetness factors of each layer.
outputFormat
Output to standard output (stdout) a single line containing T integers separated by spaces. Each integer is the minimized total sweetness difference for the corresponding cake.
## sample1
1 5
0
</p>