思路:
一道很有意思的树状数组统计题。
实现:
1 #include<bits/stdc++.h> 2 using namespace std; 3 class Fenwick{ 4 vector<int>v; 5 public: 6 Fenwick(int n){ 7 v.resize(n+2,0); 8 } 9 inline int lowbit(int x){ 10 return x&-x; 11 } 12 void upd(int x,int d){ 13 while(x<v.size()){ 14 v[x]+=d; 15 x+=lowbit(x); 16 } 17 } 18 int sum(int x){ 19 int res=0; 20 while(x){ 21 res+=v[x]; 22 x-=lowbit(x); 23 } 24 return res; 25 } 26 }; 27 int a[5005]; 28 int main() 29 { 30 int t;cin>>t; 31 while(t--){ 32 int n;cin>>n; 33 for(int i=1;i<=n;i++)cin>>a[i]; 34 long long res=0; 35 Fenwick*fl=new Fenwick(n); 36 Fenwick*fr=new Fenwick(n); 37 for(int i=1;i<=n;i++){ 38 for(int j=n;j>i;j--){ 39 int x=fl->sum(a[j]-1); 40 int y=fr->sum(a[i]-1); 41 res+=(long long)x*y; 42 fr->upd(a[j],1); 43 } 44 for(int j=i+1;j<=n;j++){ 45 fr->upd(a[j],-1); 46 } 47 fl->upd(a[i],1); 48 } 49 cout<<res<<endl; 50 } 51 return 0; 52 }