#P8613. [蓝桥杯 2014 省 B] 小朋友排队

[蓝桥杯 2014 省 B] 小朋友排队

Description

There are nn kids standing in a line. Now we want to arrange them in non-decreasing order of height (from short to tall), but each operation can only swap two adjacent kids.

Each kid has an "unhappiness" value. At the beginning, every kid’s unhappiness is 00.

If a kid is asked to swap for the first time, their unhappiness increases by 11. If they are asked to swap for the second time, their unhappiness increases by 22 (so the total becomes 33), and so on. In general, when a kid is asked to swap for the kk-th time, their unhappiness increases by kk.

Find the minimum possible total unhappiness (the sum of all kids’ unhappiness values) after making all kids line up from short to tall.

If two kids have the same height, it does not matter which one stands in front of the other.

Input Format

The first line contains an integer nn, the number of kids.

The second line contains nn integers H1,H2HnH_1,H_2 \cdots H_n, where HiH_i is the height of the ii-th kid.

Output Format

Output one line containing one integer, the minimum possible total unhappiness.

3
3 2 1
9

Hint

[Sample Explanation]

First swap the kids with heights 33 and 22, then swap the kids with heights 33 and 11, and then swap the kids with heights 22 and 11. Each kid’s unhappiness is 33, so the total is 99.

[Constraints]

For 10%10\% of the testdata, 1n101 \le n \le 10.

For 30%30\% of the testdata, 1n10001 \le n \le 1000.

For 50%50\% of the testdata, 1n100001 \le n \le 10000.

For 100%100\% of the testdata, 1n1000001 \le n \le 100000, 0Hi10000000 \le H_i \le 1000000.

Time limit: 1 second. Memory limit: 256 MB. Lanqiao Cup 2014, the 5th Provincial Contest.

Translated by ChatGPT 5