ALDS1_5_D The Number of Inversions(分而治之-归并排序)

The Number of Inversions

 

For a given sequence A={a0,a1,...an−1}A={a0,a1,...an−1}, the number of pairs (i,j)(i,j) where ai>ajai>aj and i<ji<j, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program:

bubbleSort(A)
  cnt = 0 // the number of inversions
  for i = 0 to A.length-1
    for j = A.length-1 downto i+1
      if A[j] < A[j-1]
	swap(A[j], A[j-1])
	cnt++

  return cnt

For the given sequence AA, print the number of inversions of AA. Note that you should not use the above program, which brings Time Limit Exceeded.

Input

In the first line, an integer nn, the number of elements in AA, is given. In the second line, the elements aiai (i=0,1,..n−1i=0,1,..n−1) are given separated by space characters.

output

Print the number of inversions in a line.

Constraints

  • 1≤n≤200,0001≤n≤200,000
  • 0≤ai≤1090≤ai≤109
  • aiai are all different

Sample Input 1

5
3 5 2 1 4

Sample Output 1

6

Sample Input 2

3
3 1 2

Sample Output 2

2

Source: https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_5_D


题意:求数列的逆序对

题解:分而治之的思想将数列分隔为左右两端L,R  然后从小到大排序再将L,R合并到一起时判断当R[j]<L[i]时这里于R[j]组成逆序对的个数为L的长度减去i;


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
#define clr(a) memset(a,b,sizeof(a))
#define il     inline
#define reg    register
#define rep(i,a,n) for(reg int i=a;i<n;i++)
typedef long long ll;
const int maxn=2000000+5;
const int minn=1000+5;
const int inf=2e9+2;
int n,a[maxn];
int L[maxn/2],R[maxn/2];
ll merge_t(int l,int mind,int r)
{
    ll cnt=0;
    rep(i,0,mind-l+1){L[i]=a[l+i];}
    rep(i,0,r-mind){R[i]=a[mind+i+1];}
    L[mind-l+1]=inf;R[r-mind]=inf;
    for(reg int k=l,i=0,j=0;k<=r;k++)
    {
        if(L[i]<=R[j]){a[k]=L[i++];}
        else {a[k]=R[j++];cnt+=mind-l-i+1;}
    }
    return cnt;
}
ll mergeSort(int l,int r)
{
    if(l<r)
    {
        ll v1,v2,v3;
        int mind=(l+r)>>1;
        v1=mergeSort(l,mind);
        v2=mergeSort(mind+1,r);
        v3=merge_t(l,mind,r);
        return v1+v2+v3;
    }
    else return 0;
}
int main()
{
    scanf("%d",&n);
    rep(i,1,n+1)
    {
        scanf("%d",&a[i]);
    }
    printf("%lld\n",mergeSort(1,n));
    return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值