HDU 3333

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int n, a[30005], c[30005], d[30005], k, vis[30005];
long long b[30005];
int find(int x)
{
    int l=1, r=k-1;
    while(l<=r)
    {
        int m=(l+r)>>1;
        if(c[m]==x) return m;
        if(c[m]<x) l=m+1;
        else r=m-1;
    }
    return -1;
}
bool cmp(int x,int y)
{
    return x<y;
}
struct kkk
{
    int l, r, id;
    long long ans;
} op[100005];
bool cmp2(kkk x,kkk y)
{
    if(x.r==y.r)
        return x.l<y.l;
    return x.r<y.r;
}
bool cmp3(kkk x,kkk y)
{
    return x.id<y.id;
}
int lowbit(int x)
{
    return x&(-x);
}
void add(int p,int x)
{
    while(p<=n)
    {
        b[p]+=x;
        p+=lowbit(p);
    }
}
long long  get(int p)
{
    long long ret=0;
    while(p>0)
    {
        ret+=b[p];
        p-=lowbit(p);
    }
    return ret;
}
int main()
{
    int tt, i, j, q;
    scanf("%d",&tt);
    while(tt--)
    {
        scanf("%d",&n);
        for(i=1; i<=n; i++)
            b[i]=0;
        for(i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            d[i]=a[i];
        }
        sort(d+1,d+n+1,cmp);
        k=2;
        c[1]=d[1];
        for(i=2; i<=n; i++)
        {
            if(d[i]!=d[i-1])
                c[k++]=d[i];
        }
        memset(vis,-1,sizeof(vis));
        scanf("%d",&q);
        for(i=0; i<q; i++)
        {
            scanf("%d%d",&op[i].l,&op[i].r);
            op[i].id=i;
        }
        sort(op,op+q,cmp2);
        j=1;
        int tmp;
        for(i=0; i<q; i++)
        {
            for(; j<=op[i].r; j++)
            {
                tmp=find(a[j]);
                if(vis[tmp]!=-1)
                    add(vis[tmp],-a[j]);
                add(j,a[j]);
                vis[tmp]=j;
            }
            op[i].ans=get(op[i].r)-get(op[i].l-1);
        }
        sort(op,op+q,cmp3);
        for(i=0; i<q; i++)
            printf("%I64d\n",op[i].ans);
    }
    return 0;
}

posted @ 2013-08-12 13:14  Ink_syk  阅读(124)  评论(0编辑  收藏  举报