hdu 3874(树状数组)

来源:互联网 发布:ea交易编程零基础教学 编辑:程序博客网 时间:2024/05/16 02:49
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int maxn=50010;
//离线算法
int n;
__int64 c[maxn];
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int val)
{
    for(int i=x;i<=n;i+=lowbit(i))
    {
        c[i]+=val;
    }
}
__int64 getsum(int x)
{
    __int64 cnt=0;
    for(int i=x;i>=1;i-=lowbit(i))
    {
        cnt+=c[i];
    }
    return cnt;
}




int a[maxn];
map<int,int> hash;
struct Node
{
    int l,r;
    int idx;
};
Node qu[maxn*4];
__int64 ans[maxn*4];
bool cmp(Node h,Node k)
{
    return h.r<k.r;
}


int main()
{
    int ci;scanf("%d",&ci);
    while(ci--)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        int q;
scanf("%d",&q);
        for(int i=0;i<q;i++)
        {
            int l,r;
scanf("%d%d",&l,&r);
            if(l>r) swap(l,r);
            qu[i].l=l,qu[i].r=r;
            qu[i].idx=i;
        }
        sort(qu,qu+q,cmp); //以r排序
        for(int i=1;i<=n;i++)
c[i]=0; //树状数组
        hash.clear();
        int rr=1;
        for(int i=0;i<q;i++)
        {
            while(rr<=qu[i].r)
            {
                if(hash[a[rr]]!=0)
                {
                    update(hash[a[rr]],-a[rr]);
                }
                hash[a[rr]]=rr;
                update(rr,a[rr]);
                rr++;
            }
            ans[qu[i].idx]=getsum(qu[i].r)-getsum(qu[i].l-1);
        }
        for(int i=0;i<q;i++)
printf("%I64d\n",ans[i]);
    }
    return 0;
}
原创粉丝点击