NYOJ_117_求逆序数
与前面的那题一样的做法:
#include <iostream> #include <cstdio> #include <cmath> #include<cstring> #include<vector> #include <algorithm> using namespace std; #define N 1000005 #define LL long long int c[N],n; struct point { int val,id; }p[N]; int sum(int x) { int ret=0; while(x) { ret+=c[x]; x-=(x&-x); } return ret; } void add(int x) { while(x<=n) { c[x]++; x+=(x&-x); } } bool cmp(point a,point b) { if(a.val != b.val) //必须这样写,考虑下有重复元素 return a.val<b.val; return a.id <b.id; } int main() { int t,i,j,k; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=1;i<=n;++i) { scanf("%d",&p[i].val); p[i].id=i; c[i]=0; } LL ans=0; sort(p+1,p+1+n,cmp); for(i=1;i<=n;++i) { add(p[i].id); ans+=i-sum(p[i].id); } cout<<ans<<endl; } return 0; }