#include<iostream> #include<cstdio> #include<cstring> #include<vector> using namespace std; int max(int a,int b) {return a>b?a:b;} inline int lowbit(int x) { return x&(-x);//2^k } struct Fen { int n; vector<int> c; void resize(int n) {this->n=n;c.resize(n);} void clear() {fill(c.begin(),c.end(),0);} int sum(int x) //求前 N项的和 { int r=0; while(x>0) { r+=c[x]; x-=lowbit(x); } return r; } void add(int x,int d)//求前 N项sum的和 { while(x<=n) { c[x]+=d;x+=lowbit(x); } } }; int n,a[20005],c[20005],d[20005]; Fen f; int main() { int t,i; scanf("%d",&t); while(t--) { scanf("%d",&n); memset(a,0,sizeof(a)); memset(c,0,sizeof(c)); memset(d,0,sizeof(d)); int maxs=0; for(i=1;i<=n;i++) { scanf("%d",&a[i]); maxs=max(maxs,a[i]); } f.resize(maxs+1); f.clear(); for(i=1;i<=n;i++)//前缀和 { f.add(a[i],1);//求前 N项sum的和 c[i]=f.sum(a[i]-1);//求前 N项的和 } f.clear(); for(i=n;i>=1;i--)//后缀和 { f.add(a[i],1); d[i]=f.sum(a[i]-1); } long long ans=0; for(i=2;i<n;i++) ans+=(long long)c[i]*(n-i-d[i])+(long long)d[i]*(i-1-c[i]); printf("%lld\n",ans); } return 0; }
原文地址:http://blog.csdn.net/u012346225/article/details/42128255