BIT+离散化
1 #include2 #include 3 #include 4 using namespace std; 5 int n,a[500010]; 6 int num[500010]; 7 long long ans; 8 struct node{ 9 int id,w;10 }q[500010];11 int cmp(node a,node b)12 {13 return a.w =1){21 cnt+=num[i];i-=lowbit(i);22 }23 return cnt;24 }25 void update(int i,int val){26 while(i<=n){27 num[i]+=val;i+=lowbit(i);28 }29 }30 int main()31 {32 int i,j,k;33 while(scanf("%d",&n)!=EOF){34 if(n==0) break;35 memset(num,0,sizeof(num));36 ans=0;37 for(i=1;i<=n;i++){38 q[i].id=i;39 scanf("%d",&q[i].w);40 }41 sort(q+1,q+n+1,cmp);42 for(i=1;i<=n;i++) a[q[i].id]=i;43 for(j=1;j<=n;j++)44 {45 update(a[j],1);46 ans+=j-sum(a[j]);47 }48 printf("%lld\n",ans);49 }50 return 0;51 }
1 #include2 #include
归并:
1 #include2 3 const int N=500000+10; 4 5 int n,a[N],temp[N]; 6 long long ans; 7 8 void merge_sort(int l,int r) 9 {10 if (r-l<=1) return;11 int m=(l+r)>>1;12 int p=l,q=m,i=l;13 merge_sort(l,m);14 merge_sort(m,r);15 while (p =r || (p
1 #include2 #include
这个博客 讲的很不错:http://blog.csdn.net/suwei19870312/article/details/5293694