AcWing 5910. 求逆序对
原题链接
简单
作者:
171800
,
2024-09-12 12:58:25
,
所有人可见
,
阅读 50
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int num[N], tmp[N];
long long ans = 0; //最大值n**2确实要考虑溢出的情况
//思路:归并排序里计数
void solve(int l, int r){
//定义出口
if(l == r){
return ;
}
int mid = (l + r) / 2;
//分治
solve(l, mid);
solve(mid + 1, r);
//合并
int i = l, j = mid + 1;
int k = l;
while(i <= mid && j <= r){
//注意这边的等号
if(num[i] <= num[j]){
tmp[k++] = num[i++];
}else{
ans += (long long)(mid - i + 1); //应该是和i相关,而不是j
tmp[k++] = num[j++];
}
}
while(i <= mid){
tmp[k++] = num[i++];
}
while(j <= r){
tmp[k++] = num[j++];
}
//复制数组
for(int i = l; i <= r; i++)
num[i] = tmp[i];
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> num[i];
solve(0, n - 1);
cout << ans;
return 0;
}