利用归并排序求逆序数(N(logN))

 There are N integers (1<=N<=65537) A1, A2,.. AN (0<=Ai<=10^9). You need to find amount of such pairs (i, j) that 1<=iA[j].

 Input
 The first line of the input contains the number N. The second          line contains N numbers A1...AN.

 Output
 Write amount of such pairs.

 Sample test(s)

 Input
 5 
 2 3 1 5 4

 Output
 3
#include
#include
#include

using namespace std;
const int MAX = 65537;
typedef long long int ll;

ll num[MAX+100];
ll need[MAX+100];
ll cunt = 0;

void Merge(int a,int mid,int b)
{
    int i = a,j = mid+1,k = a;

    while(i <= mid&&j <= b)
    {
        if(num[i] <= num[j])
           need[k++] = num[i++];
        else
        {
           need[k++] = num[j++];
           cunt += mid-i+1;
        }
    }
    while(i <= mid) need[k++] = num[i++];
    while(j <= b) need[k++] = num[j++];
    for(i = a;i <= b;i++)
       num[i] = need[i];

}

void Msort(int a,int b)
{
    if(a < b)
    {
        int mid = (a+b)/2;
        Msort(a,mid);
        Msort(mid+1,b);
        Merge(a,mid,b);
    }
}

int main()
{
    int N;
    scanf("%d",&N);
    ll ans = 0;
    for(int i = 0;i scanf("%lld",&num[i]);
    }
    Msort(0,N-1);
    printf("%lld\n",cunt);

    return 0;
}

你可能感兴趣的:(排序)