HDU - lines (树状数组&&离散化)

链接

用树状数组实现区间修改与单点查询,因为线段端点数据比较大,我们需要对其离散化处理.

参考代码:

#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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值