1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #include <stdio .h> #include <string .h> #include <stdlib .h> #define MAX 51000 #define MID(a,b) (a+b)>>1 #define R(a) (a< <1|1) #define L(a) a<<1 typedef struct { int num,left,right; }Node; int ans[MAX]; Node Tree[MAX<<2]; int n;
void Build(int t,int l,int r) { int mid; Tree[t].left=l,Tree[t].right=r; if(Tree[t].left==Tree[t].right) { Tree[t].num=0; return ; } mid=MID(Tree[t].left,Tree[t].right); Build(L(t),l,mid); Build(R(t),mid+1,r); }
void Insert(int t,int l,int r,int x) { int mid; if(Tree[t].left==l&&Tree[t].right==r) { Tree[t].num+=x; return ; } mid=MID(Tree[t].left,Tree[t].right); if(l>mid) { Insert(R(t),l,r,x); } else if(r< =mid) { Insert(L(t),l,r,x); } else { Insert(L(t),l,mid,x); Insert(R(t),mid+1,r,x); } Tree[t].num=Tree[L(t)].num+Tree[R(t)].num; }
int Query(int t,int l,int r) { int mid; if(Tree[t].left==l&&Tree[t].right==r) return Tree[t].num; mid=MID(Tree[t].left,Tree[t].right); if(l>mid) { return Query(R(t),l,r); } else if(r<=mid) { return Query(L(t),l,r); } else { return Query(L(t),l,mid)+Query(R(t),mid+1,r); } }
int main() { int a,n,i,t; scanf("%d",&t); long long int k; while(t--) { scanf("%d",&n); memset(Tree,0,sizeof(Tree)); Build(1,1,n); for(i=1;i<=n;i++) { scanf("%d",&ans[i]); } for(i=1,k=0;i<=n;i++) { a=ans[i]; Insert(1,a,a,1); k=k+(i-Query(1,1,a)); } printf("%lld\n",k); } return 0; }
|