逆序对

简介:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100010], t[100010];
long long ans = 0;
void merge_sort(int* a, int x, int y, int* t){
	if (y - x > 1){
		int m = x + (y - x) / 2;
		int p = x, q = m, i = x;
		merge_sort(a, x, m, t);
		merge_sort(a, m, y, t);
		while (p < m || q < y)
		    if (q >= y || (p < m && a[p] < a[q])) t[i++] = a[p++];
		    else t[i++] = a[q++], ans += m - p;
        for (int j = x; j < y; j++) a[j] = t[j];
	}
}
int main(){
	int n; cin>>n;
	for (int i = 0; i < n; i++) scanf("%d", &a[i]);
	merge_sort(a, 0, n, t);
	cout<<ans;
	return 0;
}

相关文章
|
4月前
|
测试技术
leetcode-152:乘积最大子数组
leetcode-152:乘积最大子数组
51 0
|
人工智能
1311:【例2.5】求逆序对
1311:【例2.5】求逆序对
119 0
|
C++
剑指offer 53. 数组中的逆序对
剑指offer 53. 数组中的逆序对
71 0
剑指offer 53. 数组中的逆序对
解 旋转数组
解 旋转数组
逆序对问题
逆序对问题
66 0
|
人工智能
K个逆序对数组
K个逆序对数组
【LeetCode】第4天 - 977. 有序数组的平方 | 189. 旋转数组
【LeetCode】第4天 - 977. 有序数组的平方 | 189. 旋转数组
94 0
【LeetCode】第4天 - 977. 有序数组的平方 | 189. 旋转数组
求逆序对
给出若干个数,每次可以交换相邻的两个,如果要将这些数变成非递减的数,需要操作多少次? 很容易就可以想到暴力的解决方式 如果是数据范围比较小的时候,可以直接进行暴力求解 如果是数据范围比较大的时候,这时候需要用树状数组求解一下 附上暴力的代码
98 0
|
机器学习/深度学习
剑指offer之数组中的逆序对
剑指offer之数组中的逆序对
91 0