數據結構實驗之排序五:歸併求逆序數
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
輸出逆序數。
Sample Input
10
10 9 8 7 6 5 4 3 2 1
Sample Output
45
#include <stdio.h>
int n;
int a[101000];
int t[101000];
long long ans;
void Merge(int s1,int e1,int s2,int e2)
{
int k=s1;
int p1 = s1;
int p2 = s2;
while (p1<=e1&&p2<=e2)
{
if (a[p1]<=a[p2])
{
t[k++] = a[p1++];
}
else
{
t[k++] = a[p2++];
ans+=e1-p1+1;//累加得出逆序數
}
}
while (p1<=e1)
t[k++] = a[p1++];
while (p2<=e2)
t[k++] = a[p2++];
k--;
while (k>=s1)
{
a[k] = t[k];
k--;
}
}
void MergeSort(int s,int e)
{
int k;
if (s<e)
{
k = (s+e)/2;
MergeSort(s,k);
MergeSort(k+1,e);
Merge(s,k,k+1,e);
}
}
int main()
{
int i,j;
ans = 0;
scanf ("%d",&n);
for (i=0; i<n; i++)
scanf ("%d",&a[i]);
MergeSort(0,n-1);
printf ("%lld\n",ans);//a數組中的數已經排好序了
return 0;
}