Gym-103373-C. A Sorting Problem
本题用O(nlogn)时间求逆序对,我用的归并排序求逆序对
#include <cstring>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
#define ll long long
const int M = 200020;
int str[M];
int str1[M];
ll ans = 0;
void find_(int l, int r) {
if (l + 1 == r) {
if (str[l] > str[r]) {
swap(str[l], str[r]);
ans++;
}
}
if (l == r) return;
int mid = l + r >> 1;
find_(l, mid);
find_(mid + 1, r);
int i = l, j = mid + 1, cnt = 0, cnt1 = 0;
while (i <= mid && j <= r) {
if (str[i] <= str[j]) {
str1[cnt++] = str[i++];
ans += cnt1;
}
else {
str1[cnt++] = str[j++];
cnt1++;
}
}
if (i > mid) {
while (j <= r) {
str1[cnt++] = str[j++];
}
}
else {
while (i <= mid) {
str1[cnt++] = str[i++];
ans += cnt1;
}
}
cnt = 0;
for (i = l; i <= r; ++i) {
str[i] = str1[cnt++];
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &str[i]);
find_(0, n - 1);
printf("%lld\n", ans);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律