乒乓比赛【树状数组】
树状数组水题
#include <bits/stdc++.h>
#define sc(x) scanf("%d",&x)
using namespace std;
const int maxn = 20006;
const int maxm = 1e5+50;
typedef long long ll;
int n;
int a[maxn];
int bit[maxm];
int rbit[maxm];
int c[maxn],d[maxn];
int lowbit(int t) {return t&(-t);}
void add(int i,int m)
{
while(i<maxm)
{
if(m==1)
bit[i]++;
else rbit[i]++;
i+=lowbit(i);
}
}
int sum(int i,int m)
{
int s=0;
while(i>0)
{
if(m==1)
s+=bit[i];
else s+=rbit[i];
i-=lowbit(i);
}
return s;
}
int main()
{
int T;
sc(T);
while(T--)
{
sc(n);
memset(bit,0,sizeof(bit));
memset(rbit,0,sizeof(rbit));
memset(c,0,sizeof(c));
memset(d,0,sizeof(d));
ll all =0;
for(int i=1;i<=n;i++) sc(a[i]);
for(int i=1;i<=n;i++)
{
add(a[i],1);
c[i] = sum(maxm-1,1)-sum(a[i],1);
//cout<<c[i]<<endl;
}
for(int i=n;i>=1;i--)
{
add(a[i],2);
d[i] = sum(maxm-1,2)-sum(a[i],2);
}
for(int i=1;i<=n;i++)
{
all += (ll) c[i] * (n-i-d[i]);
all += (ll)(i-1-c[i])*d[i];
}
printf("%lld\n",all);
}
return 0;
}