HDU(3333)树状数组+离线

本文介绍了一种解决区间内不重复数字总和问题的有效算法。通过离线化操作及区间树等数据结构优化,实现了对大量数据快速查询。文章详细展示了C++实现代码,并解释了如何对查询区间进行排序,以及利用前缀和思想减少计算复杂度。

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

题目大意:给出一列数字,再给出一些询问,求询问的区间中,不重复的数字的总和。

思路:数据量较大,可考虑使用离线化操作,将答案存起来一并输出。先把询问的区间右端按照从小到大排序,否则查询的时候需要多次更新数组。

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
const int maxn = 33333;
struct node
{
    int l, r;
    int id;
    bool operator < (const node &a)const
    {
        return r < a.r;
    }
}p[maxn << 2];
long long ans[maxn << 2];//存结果
long long sum[maxn << 2];
long long a[maxn], b[maxn];
long long tail[maxn];//记录该数字上次出现的坐标
int n, q;
int lowbit(int x)
{
    return x & (-x);
}
void modify(int pos, int val)
{
    for(int i=pos; i<=n; i+=lowbit(i))
    {
        sum[i] += val;
    }
    /*for(int i=1; i<=n; i++)
    {
        cout<<"sum"<<i<<" "<<sum[i]<<endl;
    }*/
}
long long query(int pos)
{
    long long res = 0;
    for(int i=pos; i>0; i-=lowbit(i))
    {
        res += sum[i];
    }
    return res;
}
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        memset(sum, 0, sizeof sum);
        memset(tail, 0, sizeof tail);
        scanf("%d", &n);
        for(int i=1; i<=n; i++)
        {
            scanf("%lld", &a[i]);
            b[i] = a[i];
        }
        scanf("%d", &q);
        for(int i=1; i<=q; i++)
        {
            scanf("%d%d", &p[i].l, &p[i].r);
            p[i].id = i;
        }
        sort(p+1, p+1+q);
        sort(b+1, b+1+n);
        int tot = 1;
        for(int i=1; i<=n; i++)
        {
            int pos = lower_bound(b+1, b+1+n, a[i]) - b;
            if(!tail[pos])//判断是否之前出现过
            {
                modify(i, a[i]);
                tail[pos] = i;
            }
            else
            {
                modify(tail[pos], a[i] * (-1));
                modify(i, a[i]);
                tail[pos] = i;
            }
            while(p[tot].r == i && tot <= q)
            {
                //printf("%lld %lld\n", query(i), query(p[tot].l - 1));
                ans[p[tot].id] = query(i) - query(p[tot].l - 1);
                tot++;
            }
        }
        for(int i=1; i<=q; i++)
        {
            printf("%lld\n", ans[i]);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值