链接
用树状数组实现区间修改与单点查询,因为线段端点数据比较大,我们需要对其离散化处理.
参考代码:
#include <bits/stdc++.h>
#define lowbit(x) (x & (-x))
using i64 = long long;
constexpr int N = 1e5 + 10;
template <typename T>
inline void read(T &f) {
f = 0; T fu = 1; char c = getchar();
while (c < '0' || c > '9') { if (c == '-') { fu = -1; } c = getchar(); }
while (c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); }
f *= fu;
}
int tree[N << 1], a[N << 1], n;
struct node {
int x, y;
}s[N];
i64 sum(int x) {
i64 ans = 0;
for (int i = x; i >= 1; i -= lowbit(i)) {
ans += tree[i];
}
return ans;
}
void add(int i, int x) {
for (; i <= 2 * n; i += lowbit(i)) {
tree[i] += x;
}
}
int main() {
int t; read(t);
while (t--) {
read(n);
std::memset(tree, 0, sizeof tree);
//把树状数组清零
int k = 0;
for(int i = 0; i < n; i++) {
read(s[i].x), read(s[i].y);
a[k++] = s[i].x;
a[k++] = s[i].y;
}
std::sort(a, a + k);
for (int i = 0; i < n; i++) {
//离散化,用排序后的数的顺序代替。
s[i].x = std::lower_bound(a, a + k, s[i].x) - a + 1;
s[i].y = std::lower_bound(a, a + k, s[i].y) - a + 1;
}
for (int i = 0; i < n; i++) {
add(s[i].x, 1);
add(s[i].y + 1, -1);
}
i64 res = -1;
for (int i = 1; i <= 2 * n; i++) {
//离散化后最多n*2个点
res = std::max(res, sum(i));
}
printf("%lld\n", res);
}
return 0;
}