逆序对模板

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=550005;
int n,a[N],c[N];
long long ans;
void ready()
{
  cin>>n;
  for(int i=1;i<=n;i++)
    cin>>a[i];
}
inline void msort(int l,int r)
{
  if(l==r)return;
  int mid=(l+r)>>1;
  msort(l,mid);msort(mid+1,r);
  int i=l,j=mid+1,k=l;
  while(i<=mid&&j<=r){
    if(a[i]<=a[j])
      c[k++]=a[i++];
    else{
      c[k++]=a[j++];
      ans+=(mid-i+1);
    }
  }
  while(i<=mid)c[k++]=a[i++];
  while(j<=r)c[k++]=a[j++];
  for(i=l;i<=r;i++)
    a[i]=c[i];
}
void work()
{
  msort(1,n);
  cout<<ans<<endl;
}
int main()
{
  std::ios::sync_with_stdio(false);
  ready();work();return 0;
}

 

posted @ 2018-09-12 22:18  勿忘安己  阅读(116)  评论(0编辑  收藏  举报