- 【例2.5】求逆序对
-TJ
- 2024-2-3 12:58:09 @
/* created by chjshen, date: 2024-02-03 12:39 */
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define ls (fa << 1)
#define rs (fa << 1 | 1)
const int N = 1E5 + 5;
int n, a[N], b[N];
struct SegmentTree
{
int l, r, sum;
} t[N << 2];
void build(int fa, int L, int R)
{
t[fa].l = L, t[fa].r = R;
t[fa].sum = 0;
if (L == R) return;
int mid = (L + R) >> 1;
build(ls, L, mid);
build(rs, mid + 1, R);
}
void update(int fa, int x)
{
if (t[fa].l == t[fa].r)
{
t[fa].sum++;
return;
}
int mid = (t[fa].l + t[fa].r) >> 1;
if (x <= mid) update(ls, x);
if (mid < x) update(rs, x);
t[fa].sum = t[ls].sum + t[rs].sum;
}
long long query(int fa, int l, int r)
{
if (l <= t[fa].l && t[fa].r <= r)
{
return t[fa].sum;
}
long long ans = 0;
int mid = (t[fa].l + t[fa].r) >> 1;
if (l <= mid) ans += query(ls, l, r);
if (mid < r) ans += query(rs, l, r);
return ans;
}
void handle(void)
{
long long ans = 0;
for (int i = n; i > 0; i--)
{
update(1, a[i]);
ans += query(1, 1, a[i] - 1);
}
cout << ans << endl;
}
void initInput(void)
{
ios::sync_with_stdio(0);
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
b[i] = a[i];
}
build(1, 1, n); // 建立线段树
// 离散化处理
// 1. sort
sort(b + 1, b + n + 1);
// 2. 去重
int m = unique(b + 1, b + n + 1) - b;
// 3.重新对a数组赋值
for (int i = 1; i <= n; i++) a[i] = lower_bound(b + 1, b + m + 1, a[i]) - b;
}
int main(void)
{
initInput();
handle();
return 0;
}
14 条评论
-
sunzenghang LV 5 @ 2024-10-9 15:37:38
hp
-
2024-6-4 12:40:14@
hp
-
2024-2-3 13:11:10@
hp
-
2024-2-3 13:05:52@
$\small\texttt{\color{#FA4129}本}\huge\texttt{\color{#FE9019}人}_{\small\texttt{\color{#FFE304}的}^{\large\texttt{\color{#FFEC01}萌\color{#FFF900}新}\small\texttt{\color{#FCFB03}Q\color{#F8FB07}A\color{#F1FB0B}Q}}}^{\large\texttt{\color{#FFB511}是}{\small\texttt{\color{#FFDC07}刚\color{#FFEF00}学}\large\texttt{\color{#FFF600}O\color{#FFFA00}I}}}\huge\texttt{\color{#E6F911}但\color{#92E82F}是}^{\large\texttt{\color{#39D54B}即}{\small\texttt{\color{#03C767}使}}}_{\normalsize\texttt{\color{#07C964}是\color{#00C789}这\color{#00C7A5}样}}\texttt{\color{#00CBC6}我\color{#00D0EB}也}^{\small\texttt{\color{#00D0F2}要}\normalsize\texttt{\color{#00D0F6}用}\texttt{\color{#03BEF4}蒟}_{\texttt{\color{#04AAEF}蒻}\large\texttt{\color{#078DE4}的}}}_{\scriptsize\texttt{\color{#01CDF6}声\color{#03C2F5}音\color{#04B4F2}大\color{#04A7EE}声\color{#0791E6}喊\color{#0A7BDD}出}}\mathcal{\color{#125BCD}hp\color{#3D2AB5}is\color{#A011AD}mine}$
-
2024-2-3 13:05:49@
hp
-
2024-2-3 13:02:05@
HP
-
2024-2-3 13:00:16@
qp
-
2024-2-3 12:59:32@
qhp
-
2024-2-3 12:58:34@
zp
-
2024-2-3 12:58:32@
-
2024-2-3 12:58:22@
qp
-
2024-2-3 12:58:17@
qp
-
2024-2-3 12:58:17@
qp
-
2024-2-3 12:58:16@
qp
- 1
信息
- ID
- 2294
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 7
- 标签
- 递交数
- 157
- 已通过
- 36
- 上传者