HDU 3874 离线处理,树状数组


题意:查询区间不相同数的集合。

思路:对于每一个查询区间,按照右端点排序,这样我们每次查询的时候,如果这个数在之前出现过,那么的话将前面的删除,重新在新的位置加入。这样每一种数只会被统计一次,查询直接用树状数组进行就行了,相当于前缀和。


#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<cmath>
#include<map>
#include<cstring>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define fi first
#define se second
#define INF 0x3f3f3f3f
#define clr(x,y) memset(x,y,sizeof x)
#define PI acos(-1.0)
#define ITER set<int>::iterator
const int Mod = 1e9 + 7;
const int maxn = 1e6 + 10;

struct Node
{
    bool operator < (const Node& t)const{return y < t.y;}
    int x,y,id;
}b[maxn];
ll a[maxn],ans[maxn];
ll tree[maxn];
int lowbit(int x){return x & (-x);}
ll get(int x){ll ret = 0;for(int i = x;i > 0; i -= lowbit(i))ret += tree[i];return ret;}
void update(int x,ll y){for(int i = x; i < maxn; i += lowbit(i))tree[i] += y;}
int vis[maxn];
int main()
{
    int Tcase;scanf("%d",&Tcase);
    while(Tcase --)
    {
        int n,m;scanf("%d",&n);for(int i = 1;i <= n;i ++)scanf("%I64d",&a[i]);clr(tree,0);
        scanf("%d",&m);for(int i = 1;i <= m; i ++)scanf("%d%d",&b[i].x,&b[i].y),b[i].id = i;sort(b + 1,b + m + 1);
        clr(vis,0);int pos = 1;
        for(int i = 1; i <= m; i ++)
        {
            while(pos <= b[i].y)
            {
                ll x = a[pos];
                if(vis[x])
                    update(vis[x],-x),vis[x] = pos,update(pos,x);
                else vis[x] = pos,update(pos,x);
                pos ++;
            }
            ans[b[i].id] = get(b[i].y) - get(b[i].x - 1);
        }
        for(int i = 1;i <= m;i ++)printf("%I64d\n",ans[i]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值