题目描述:
n 个小朋友站成一排。现在要把他们按身高从低到高的顺序排列,但是每次只能交换位置相邻的两个小朋友。
每个小朋友都有一个不高兴的程度。开始的时候,所有小朋友的不高兴程度都是0。
如果某个小朋友第一次被要求交换,则他的不高兴程度增加1,
如果第二次要求他交换,则他的不高兴程度增加2(即不高兴程度为3),依次类推。
当要求某个小朋友第k次交换时,他的不高兴程度增加k。
请问,要让所有小朋友按从低到高排队,他们的不高兴程度之和最小是多少。
如果有两个小朋友身高一样,则他们谁站在谁前面是没有关系的。
样例说明
首先交换身高为3和2的小朋友,再交换身高为3和1的小朋友,
再交换身高为2和1的小朋友,每个小朋友的不高兴程度都是3,总和为9。
数据规模和约定
对于100%的数据,1< =n< =100000,0< =Hi< =1000000。
输入:
输入的第一行包含一个整数n,表示小朋友的个数。
第二行包含 n 个整数 H1 H2 … Hn,分别表示每个小朋友的身高。
输出:
输出一行,包含一个整数,表示小朋友的不高兴程度和的最小值。
样例输入:
3
3 2 1
样例输出:
9
参考解答:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
long[] sum = new long[n];
Arrays.fill(sum, 0);
int max = 0;
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
if (max < array[i]) {
max = array[i];
}
}
int[] tree = new int[max + 2];
Arrays.fill(tree, 0);
for (int i = 0; i < n; i++) {
update(array[i] + 1, 1, tree);
sum[i] += (i + 1) - sum(array[i] + 1, tree);
}
Arrays.fill(tree, 0);
for (int i = n - 1; i >= 0; i--) {
update(array[i] + 1, 1, tree);
sum[i] += sum(array[i], tree);
}
long result = 0;
for (int i = 0; i < n; i++) {
result += sum[i] * (sum[i] + 1) / 2;
}
System.out.println(result);
}
private static int lowbit(int x) {
//return x - (x & (x - 1));
return x & -x;
}
private static int sum(int x, int[] tree) {
int sum = 0;
for (; x >= 1; sum += tree[x], x -= lowbit(x));
return sum;
}
private static void update(int x, int add, int[] tree) {
for (; x <= tree.length - 1; tree[x] += add, x += lowbit(x));
}
}