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

版权声明:Dream_dog专属 https://blog.csdn.net/Dog_dream/article/details/83302740

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;
}

猜你喜欢

转载自blog.csdn.net/Dog_dream/article/details/83302740