BIT的应用,动态更新数组求前缀和
#include <stdio.h>
#include <string.h>
const int max_n = 100000+5;
int sum[max_n];
int arr[20005];
int c[20005];
int d[20005];
int lowbit(int n){
return n&((-1)*n);
}
int _sum(int n_index, int *sum){
int num;
int ret;
num = n_index;
while(num > 0){
ret += sum[num];
num = num-lowbit(num);
}
return ret;
}
void _add(int n_index, int add_v, int *sum){
int num;
num = n_index;
while(num <= max_n){
sum[num] += add_v;
num = num+lowbit(num);
}
}
void func(int n){
int i, j, t;
long long ret;
//calculate c[i]
memset(sum, 0, sizeof(int)*max_n);
for(i=1; i<=n; i++){
_add(arr[i], 1, sum);
c[i] = _sum(arr[i]-1, sum);
}
//calculate d[i]
memset(sum, 0, sizeof(int)*max_n);
for(i=n; i>=1; i--){
_add(arr[i], 1, sum);
d[i] = _sum(arr[i]-1, sum);
}
//get the result
ret = 0;
for(i=1; i<=n; i++){
ret += ( (long long)c[i]*(n-i-d[i]) + (long long)d[i]*(i-c[i]-1) );
}
printf("%lld\n", ret);
}
int main(void){
int t, n, i;
//freopen("input.dat", "r", stdin);
scanf("%d", &t);
while(t--){
scanf("%d", &n);
for(i=1; i<=n; i++)
scanf("%d", arr+i);
func(n);
}
return 0;
}