Luogu P1637 三元上升子序列

题目描述

https://www.luogu.com.cn/problem/P1637

简单题意:求满足 a[i]<a[j]<a[k]的点集(i,j,k)的个数

Solution

我们按照用树状数组求逆序对时的思路

做两遍树状数组即可

时间复杂度 $O(nlogn)$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cstdio>
#include <algorithm>
#define maxn 30010
#define ll long long
#define lowbit(i) ((i) & (-i))
using namespace std;

int n, a[maxn];

int b[maxn], cnt;
void init_hash() {
for (int i = 1; i <= n; ++i) b[i] = a[i];
sort(b + 1, b + n + 1); cnt = unique(b + 1, b + n + 1) - b - 1;
for (int i = 1; i <= n; ++i) a[i] = lower_bound(b + 1, b + cnt + 1, a[i]) - b;
}

struct Bit {
int n, Bit[maxn];

inline void add(int i, int v) { while (i <= n) Bit[i] += v, i += lowbit(i); }

inline int get_sum(int i) {
int s = 0;
while (i) s += Bit[i], i -= lowbit(i);
return s;
}
} B1, B2;

int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
init_hash(); B1.n = B2.n = cnt; ll ans = 0;
for (int i = 1; i <= n; ++i) {
B2.add(a[i], B1.get_sum(a[i] - 1));
B1.add(a[i], 1);
ans += B2.get_sum(a[i] - 1);
}
cout << ans << endl;
return 0;
}