4709 三元组

这篇博客介绍了如何利用树状数组(也称作 BIT,Binary Indexed Tree)来高效地处理区间内的数据查询与修改。文章通过一个实例展示了如何在O(logn)的时间复杂度内完成对数个元素的累加查询与更新操作,从而实现快速的数据统计。内容包括树状数组的基本定义、lowbit 函数的实现、add 和 query 函数的详细解释,以及在求解区间问题上的应用。

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

在这里插入图片描述
树状数组

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 1e6 + 10;

typedef long long LL;

int n;
int a[N], xs[N], tr[N];

int lowbit(int x)
{
    return x & -x;
}

void add(int x, int c)
{
    for(int i = x; i <= n; i += lowbit(i))
        tr[i] += c;
}

int query(int x)
{
    int res = 0;
    for(int i = x; i; i -= lowbit(i))
        res += tr[i];
    return res;
}

int main()
{
    cin >> n;
    for(int i = 0; i < n; i ++)
    {
        cin >> a[i];
        xs[i] = a[i];
    }
    sort(xs, xs + n);
    
    LL res = 0;
    for(int i = 0; i < n; i ++)
    {
        int t = lower_bound(xs, xs + n, a[i]) - xs + 1;
        int q = query(t); //前面小于等于a[i]的数量
        
        res += (LL)(i - q) * (t - 1 - q); //前面大于 a[i] * 后面小于a[i] 数量
        add(t, 1);
    }
    cout << res << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值