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

来源:互联网 发布:什么是网络成瘾 编辑:程序博客网 时间:2024/06/03 20:57

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

Time Limit: 50MS Memory Limit: 65536KB
SubmitStatistic

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 

实际上归并排序的交换次数就是这个数组的逆序对个数,为什么呢?


我们可以这样考虑:


归并排序是将数列a[l,h]分成两半a[l,mid]和a[mid+1,h]分别进行归并排序,然后再将这两半合并起来。

在合并的过程中(设l<=i<=mid,mid+1<=j<=h),当a[i]<=a[j]时,并不产生逆序数;当a[i]>a[j]时,在

前半部分比a[i]大的数都比a[j]大,将a[j]放在a[i]前面的话,逆序数要加上mid+1-i。因此,可以在归并

序中的合并过程中计算逆序数.


#include<stdio.h>#include<string.h>#include<stdlib.h>long long int sum; //此题必须long long才对void Merge(int a[], int b[], int i, int m, int n)//2-路归并排序{    int j, k;    int x;    x = i;    for(j = i, k = m+1; j <= m && k <= n; x++)    {        if(a[j] <= a[k])        {            b[x] = a[j];            j++;        }        else        {            b[x] = a[k];            k++;            sum += m - j + 1;        }    }    while(j<=m)    {       b[x++] = a[j++];    }    while(k <= n)    {        b[x++] = a[k++];    }    for(k = i; k <= n; k++) //将排列好的两半序列再放入原序列中, 这样才能继续归并排序
        a[k] = b[k];        //b[k]只是暂存排列好的数据的一段空间    }void MSort(int a[], int b[], int s, int t)//归并排序{    int m;    if(s == t)        b[s] = a[s];    else    {        m = (s+t)/2;        MSort(a, b, s, m);        MSort(a, b, m+1, t);        Merge(a, b, s, m, t);    }}int main(){    int n, i;    int a[100010], b[100010];    sum = 0;    scanf("%d", &n);    for(i = 1; i <= n; i++)    {        scanf("%d", &a[i]);    }    MSort(a, b, 1, n);    printf("%lld\n", sum);    return 0;}



原创粉丝点击