当前位置:网站首页>逆序对的数量
逆序对的数量
2022-08-04 22:33:00 【Ding Jiaxiong】
题目
给定一个长度为 n 的整数数列,请你计算数列中的逆序对的数量。
逆序对的定义如下:对于数列的第 i 个和第 j 个元素,如果满足 i<j 且 a[i]>a[j],则其为一个逆序对;否则不是。
输入格式
第一行包含整数 n,表示数列的长度。
第二行包含 n 个整数,表示整个数列。
输出格式
输出一个整数,表示逆序对的个数。
数据范围
1≤n≤100000,
数列中的元素的取值范围 [1,109]。
输入样例:
6
2 3 4 5 6 1
输出样例:
5
思路分析



题解
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long LL;
const int N = 100010;
int n;
int q[N],tmp[N];
LL merge_sort(int l , int r){
if(l >= r){
return 0;
}
int mid = (l + r) / 2;
LL res = merge_sort(l , mid) + merge_sort(mid + 1,r);
//归并的过程
int k = 0 , i = l , j = mid + 1;
while(i <= mid && j <= r){
if(q[i] <= q[j]){
tmp[k++] = q[i ++];
}
else{
tmp[k++] = q[j ++];
res += mid - i + 1;
}
}
while(i <= mid){
tmp[k ++] = q[i ++];
}
while(j <= r){
tmp[k ++] = q[j ++];
}
for(int i = l , j = 0 ; i <= r; i++ , j ++){
q[i] = tmp[j];
}
return res;
}
int main(){
cin >> n;
for(int i = 0; i < n; i++){
cin >> q[i];
}
cout << merge_sort(0 , n - 1) << endl;
return 0;
}

边栏推荐
- [Linear Algebra 02] 2 interpretations of AX=b and 5 perspectives of matrix multiplication
- 【论文笔记KDD2021】MixGCF: An Improved Training Method for Graph Neural Network-based Recommender Systems
- the warmest home
- 祝福一路顺风
- Redisson
- Several ways for rk3399 to drive screen parameters
- 最温馨的家园
- How to make a video gif?Try this video making gif artifact
- Reconfigure the ffmpeg plugin in chrome
- 现在学习次世代3D游戏建模还能找到高薪好工作吗
猜你喜欢
随机推荐
快速web开发框架——learun framework
【3D建模制作技巧分享】ZBrush模型制作流程:地精
BUG | The interface returns abnormal data
正则表达式绕过
期货开户哪个平台好,要正规安全的
字节跳动秋招提前批高频面试问题汇总!(内附答案!)
Redisson
生成回文数
OC-拷贝
养殖虚拟仿真软件提供高沉浸式的虚拟场景互动操作体验学习
The use and principle of CountDownLatch
1、网页结构
BUG | 接口返回异常数据
JVM内存配置参数GC日志
【2020】【论文笔记】超表面:多功能和可编程——
JVM memory configuration parameter GC log
Autowired自动装配
湖仓一体电商项目(五):内网穿透工具-网云穿
【3D建模制作技巧分享】ZBrush如何设置笔刷快捷键
good luck
![[Linear Algebra 02] 2 interpretations of AX=b and 5 perspectives of matrix multiplication](/img/38/764b447cf7d886500a9b99d7679cb6.png)








