$$\color{Red}{逆序对的个数-三种语言代码}$$
我的网站=> 分享了我关于前后端的各种知识和生活美食~
我于Acwing平台分享的零散刷的各种各样的题
题目介绍
给定一个长度为 n 的整数数列,请你计算数列中的逆序对的数量。
逆序对的定义如下:对于数列的第 i 个和第 j 个元素,如果满足 i < j 且 a[i] > a[j]
,则其为一个逆序对;否则不是。
输入格式
第一行包含整数 n,表示数列的长度。
第二行包含 n 个整数,表示整个数列。
输出格式
输出一个整数,表示逆序对的个数。
数据范围
1 ≤ n ≤ 100000
数列中的元素的取值范围 [1, 10 ^ 9]
输入样例:
6
2 3 4 5 6 1
输出样例:
5
java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N = 100010, n;
static int[] a = new int[N];
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long merge_sort(int l, int r, int[] a) {
if (l >= r) return 0;
int mid = l + r >> 1;
long res = merge_sort(l, mid, a) + merge_sort(mid + 1, r, a);
int [] back = new int[r - l + 1];
int i = l, j = mid+1, k = 0;
while (i <= mid && j <= r){
if (a[i] <= a[j]) back[k++] = a[i++];
else {
back[k++] = a[j++];
res += mid - i + 1;
}
}
while (i <= mid) back[k++] = a[i++];
while (j <= r) back[k++] = a[j++];
i = l;
j = 0;
while (i <= r) a[i++] = back[j++];
return res;
}
public static void main(String[] args) throws IOException {
n = Integer.parseInt(br.readLine());
String [] s = br.readLine().split(" ");
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]);
System.out.println(merge_sort(0, n-1, a));
}
}
python3 代码
def merge_sort(l, r, q):
if l >= r:
return 0
mid = l + r >> 1
res = merge_sort(l, mid, q) + merge_sort(mid+1, r, q)
i, j = l, mid+1
tem = []
while i <= mid and j <= r:
if q[i] <= q[j]:
tem.append(q[i])
i += 1
else:
tem.append(q[j])
j += 1
res += mid - i + 1
#剩余归并
while i <= mid:
tem.append(q[i])
i += 1
while j <= r:
tem.append(q[j])
j += 1
q[l:r+1] = tem
return res
if __name__ == '__main__':
n = int(input())
data = [int(x) for x in input().split()]
print(merge_sort(0, n-1, data))
C++ 代码
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int n,a[N],tem[N];
typedef long long LL;
LL merge_sort(int a[], int l, int r)
{
if(l >= r) return 0;
int mid=l+r>>1;
LL res = merge_sort(a,l,mid) + merge_sort(a,mid+1,r);
int i=l, j=mid+1, k=0;
while(i<=mid && j<=r)
{
if(a[i]<=a[j]) tem[k++] = a[i++];
else tem[k++] = a[j++], res += mid - i + 1;
}
//剩余归并
while(i<=mid) tem[k++] = a[i++];
while(j<=r) tem[k++] = a[j++];
for(int i=l,j=0;i<=r;i++,j++) a[i] = tem[j];
return res;
}
int main()
{
cin >> n;
for(int i=0; i<n; i++) cin >> a[i];
cout << merge_sort(a, 0, n-1);
return 0;
}