數據結構實驗之排序五:歸併求逆序數
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
10 10 9 8 7 6 5 4 3 2 1
Example Output
45
Hint
Author
#include <iostream>
#include <bits/stdc++.h>
#include <stdio.h>
#define N 100000
using namespace std;
long long ans;
int a[N],temp[N];
void merge(int s1, int e1, int s2, int e2)
{
int p, p1, p2;
p = 0; p1 = s1; p2 = s2;
while(p1 <= e1 && p2 <= e2)
{
if(a[p1] <= a[p2])
{
temp[p++] = a[p1++];
}
else
{
temp[p++] = a[p2++];
ans += e1 - p1 + 1;
}
}
while(p1<=e1)
{
temp[p++] = a[p1++];
}
while(p2<=e2)
{
temp[p++] = a[p2++];
}
int i ;
for(i =s1; i<= e2;i++)
{
a[i] = temp[i-s1];
}
}
void merge_sort(int s, int e)
{
int m;
if(s < e)
{
m = (s+e)/2;
merge_sort(s,m);
merge_sort(m+1,e);
merge(s,m,m+1,e);
}
}
int main()
{
int n, i;
ans = 0;
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
merge_sort(0, n-1);
printf("%lld\n", ans);
return 0;
}