树状数组找出[1,r]中比x小的数的个数

本文介绍了如何利用树状数组(也称作线段树)来快速查找区间 [1, r] 内小于特定值 x 的数的个数。通过树状数组的构造和更新操作,可以实现对区间查询的高效解答。" 127083007,10320444,O(1)时间复杂度删除链表节点的方法,"['数据结构', '链表操作']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <bits/stdc++.h>
using namespace std;
#define FOR0(a,b) for(int i = a; i < b; ++i)
#define FORE(a,b) for(int i = a; i <= b; ++i)
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 3e5+5;
int n,m,tot;
ll a[maxn];
ll pre[maxn];
ll c[maxn];
int f(ll x) {
    return int(lower_bound(pre,pre+tot,x)-pre)+1;
}
int lowbit(int x) {
    return x&(-x);
}
void add(int x) {
    while(x <= tot+1) {
        c[x] += 1;
        x += lowbit(x);
    }
}
ll sum(int x) {
    ll ret = 0;
    while(x > 0) {
        ret += c[x];
        x -= lowbit(x);
    }
    return ret;
}
int main() {
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n; ++i) {
        scanf("%lld", &a[i]);
    }
    for(ll i = 1; i <= n; ++i) {
        a[i] += a[i-1];
        pre[i] = a[i];
    }
    sort(pre,pre+n+1);
    tot = unique(pre,pre+n+1)-pre;
    add(f(0));
    ll ans = 0;
    for(int i = 1; i <= n; ++i) {
        ll t = upper_bound(pre,pre+tot,a[i]-m)-pre;
        // cout << a[i]-m <<" " << t << endl;
        ans += sum(tot+1)-sum(t);
        add(f(a[i]));
        // cout << ans << endl;
    }
    cout << ans << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值