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>
#include <string.h>
long long a[100005], t[100005], re;
void add(long long s1, long long e1, long long s2, long long e2)
{
long long top, num1, num2, num, i;
top = 0;
num1 = s1;
num2 = s2;
while(num1<=e1&&num2<=e2)
{
if(a[num1]<=a[num2]) t[top++] = a[num1++];
else
{
t[top++] = a[num2++];
re = re + (e1-num1+1);
}
}
while(num1<=e1)
{
t[top++] = a[num1++];
}
while(num2<=e2)
{
t[top++] = a[num2++];
}
num = 0;
for(i=s1; i<=e2; i++)
{
a[i] = t[num++];
}
}
void Sort(long long left, long long right)
{
if(left>=right) return;
else
{
long long mid;
mid = (left + right) / 2;
Sort(left, mid);
Sort(mid+1, right);
add(left, mid, mid+1, right);
}
}
int main()
{
long long n, i;
scanf("%lld", &n);
for(i=0;i<n;i++)
{
scanf("%lld", &a[i]);
}
re = 0;
Sort(0, n-1);
printf("%lld\n", re);
return 0;
}