題目鏈接:
題目解析:
考慮第i個人當裁判,設此時左邊又x個人比他小,右邊有y個人比他小。那麼,他能組織x*(n-i-y)+(i-1-x)*y場比賽把n個人的場次累加即可。
接下來考慮如何求x和y。從左到右掃描數組,設a[j]表示目前爲止數字j出現了幾次,則x就是。類似的,可以求出y。
這個修改、求和的過程就要用到樹狀數組。
AC代碼(網站好像有問題......最近一頁這道題都是WA):
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 100000 + 100;
int t, n, a[maxn], c[maxn], b[maxn], d[maxn];
inline int lowbit(int x){
return x&-x;
}
void add(int x){
while(x<=maxn){
c[x] += 1;
x += lowbit(x);
}
}
int sum(int x){
int ret = 0;
while(x > 0){
ret += c[x];
x -= lowbit(x);
}
return ret;
}
int main(){
cin>>t;
while(t--){
cin>>n;
for(int i=1; i<=n; ++i) cin>>a[i];
memset(c, 0, sizeof(c));
for(int i=1; i<=n; ++i){
add(a[i]);
b[i] = sum(a[i]-1);
}
memset(c, 0, sizeof(c));
for(int i=n; i>0; --i){
add(a[i]);
d[i] = sum(a[i]-1);
}
long long ans = 0;
for(int i=1; i<n; ++i){
ans += (long long)b[i]*(n-i-d[i]) + (long long)(i-b[i]-1)*d[i];
}
cout<<ans<<endl;
}
return 0;
}