題目:
現在給定一個有 N 個數的數列 Ai。若對於 i < j,有 Ai > Aj,則稱 (i, j) 爲數列的一個逆序對。
例如,<2, 3, 8, 6, 1> 有五個逆序對,分別是 (1, 5), (2, 5), (3, 4), (3, 5), (4, 5)。
現在請你求出一個給定數列的逆序對個數。
提示:排序算法可以解決這個問題。
輸入格式
一個整數 T,表示有多少組測試數據。
每組測試數據第一行是一個正整數 N (1 <= N <= 100000),表示數列中有 N 個數字。
接下來一行包含 N 個正整數,代表對應的數列。
保證所有正整數小於 100000000。
輸出格式
對於每組數據,輸出一行,表示逆序對的個數。
樣例輸入
1
5
2 3 8 6 1
樣例輸出
5
注意:
本題如果用普通的雙重循環遍歷求解問題,時間複雜度爲O(n^2)會導致超時;
採用歸併排序,時間複雜度爲O(nlogn)不會超時;
有一個小陷阱,就是逆序對的個數可能會超過int的範圍,因爲若整數序列是從100,000,000遞減,那麼逆序對的個數就會是
100,000,000*(100,000,000+1)/2, 所以需要將其設置爲long long 類型。
下面是本人的代碼:
#include<stdio.h>
#include<malloc.h>
#define MAX 100000
int N;
long long count;
int a[MAX];
void print(int a[])
{
int i;
for(i=0;i<N;i++)
printf("%d ",a[i]);
printf("\n");
}
void merge(int a[], int low,int mid, int high)
{
//printf("對下標%d--%d排序\n",low,high);
int* temp=(int*)malloc(sizeof(int)*(high-low+1));
int i=low, j=mid+1,ti=0;
while(i<=mid && j<=high)
{
if(a[i]<=a[j])
temp[ti++]=a[i++];
else
{
temp[ti++]=a[j++];
count=count+(mid-i+1); //關鍵:如果a[i]>a[j], 那麼a[i]到a[mid]都大於a[j], 逆序對個數增加mid-i+1個
}
}
while(i<=mid)
{
temp[ti++]=a[i++];
count+=high-j+1;
}
while(j<=high)
temp[ti++]=a[j++];
for(i=0;i<ti;i++)
a[low+i]=temp[i];
//print(a);
}
void mergeSort(int a[], int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
mergeSort(a,low,mid);
mergeSort(a,mid+1,high);
merge(a,low,mid,high);
}
}
void testTwo()
{
int i, j;
scanf("%d",&N);
for(i=0;i<N;i++)
scanf("%d",&a[i]);
mergeSort(a,0,N-1);
//printf("排序結果:\n");
//for(i=0;i<N;i++)
//printf("%d ",a[i]);
printf("%lld\n",count);
};
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
count=0;
testTwo();
}
}
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+5;
typedef long long LL;
int n, a[N], b[N];
LL merge_sort(int l, int r) {
if (l + 1 == r) return 0;
int m = (l + r) / 2;
LL ret = merge_sort(l, m) + merge_sort(m, r);
for (int i = l, j = m, k = l; k < r; ++k)
if (i == m) b[k] = a[j++];
else if (j == r) b[k] = a[i++];
else if (a[i] <= a[j]) b[k] = a[i++];
else b[k] = a[j++], ret += m - i;
for (int i = l; i < r; ++i) a[i] = b[i];
return ret;
}
int main() {
int T; cin >> T;
while (T--) {
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
LL ans = merge_sort(0, n);
cout << ans << endl;
}
}