数据结构实验之排序五:归并求逆序数

来源:互联网 发布:手机家装软件 编辑:程序博客网 时间:2024/05/21 11:28

Problem Description

对于数列a1,a2,a3…中的任意两个数ai,aj (i < j),如果ai > aj,那么我们就说这两个数构成了一个逆序对;在一个数列中逆序对的总数称之为逆序数,如数列 1 6 3 7 2 4 9中,(6,4)是一个逆序对,同样还有(3,2),(7,4),(6,2),(6,3)等等,你的任务是对给定的数列求出数列的逆序数。

Input

输入数据N(N <= 100000)表示数列中元素的个数,随后输入N个正整数,数字间以空格间隔。

 

Output

输出逆序数。

Example Input

1010 9 8 7 6 5 4 3 2 1

Example Output

45

Hint

Author

xam
#include<stdio.h>#include<string.h>#define N 100000int a[N];int b[N];long long int num;void Merge(int i, int m, int n){    int k = 0, j;     int s1 = i;    for(j = m + 1; i <= m && j <= n; k++)    {        if(a[i] <= a[j])        {            b[k] = a[i++];        }        else        {            b[k] = a[j++];            num = num + m - i + 1;        }    }    while(j <= n)    {        b[k++] = a[j++];    }    while(i <= m)    {        b[k++] = a[i++];    }    for(int z = s1; z <= n; z++)    {        a[z] = b[z - s1];    }}void Msort(int s, int t){    int m;    if(s == t)    {        b[s] = a[s];    }    else    {        m = (s + t) / 2;        Msort(s, m);        Msort(m + 1, t);        Merge(s, m, t);    }}int main(){    int n, i;    scanf("%d", &n);    for(i = 0; i < n; i++)    {        scanf("%d", &a[i]);    }    num = 0;    Msort(0, n - 1);    printf("%lld\n", num);    return 0;}

欢迎提建议


阅读全文
0 0
原创粉丝点击