当前位置:网站首页>逆序对的数量
逆序对的数量
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;
}

边栏推荐
猜你喜欢
随机推荐
Both synchronized and ReentrantLock are smooth, because they are reentrant locks, and a thread will not deadlock if it takes the lock multiple times. We need reentrant locks
LocalDateTime的详细使用方法
Debian防火墙的开关以及状态
【模拟面试-10年工作】项目多一定是优势吗?
Qt面试题整理
VC bmp文件总结
Rt-thread [二] 系统初始化流程
【3D建模制作技巧分享】ZBrush如何设置笔刷快捷键
Nacos配置中心之客户端长轮询
测试薪资这么高?刚毕业20K,仅需3.5个月
中国的顶级黑客在国际上是一个什么样的水平?
The upgrade and transformation plan of the fortress machine for medium and large commercial banks!Must see!
Latex快速插入作者ORCID
CountDownLatch使用及原理
【游戏建模模型制作全流程】使用ZBrush制作骷髅王
3D建模师为了让甲方爸爸过稿,还可以这么做,就是在赚血汗钱啊
Open source summer | Cloud server ECS installs Mysql, JDK, RocketMQ
JVM内存配置参数GC日志
养殖虚拟仿真软件提供高沉浸式的虚拟场景互动操作体验学习
ctfshow终极考核web654









