hdu3874

时间:2021-11-13 05:48:26

题解:

和上一题基本相同

插入的时候变一下数值

具体看http://www.cnblogs.com/xuanyiming/p/7921926.html

代码:

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=;
typedef long long ll;
struct Tree
{
ll num;
int ls,rs;
}T[N*];
int now,rt[N],la[N*],n,m,cnt=,x,y,k,a[N];
int build(int l,int r)
{
now++;
if (l==r)return now;
int k=now,mid=(l+r)/;
if (l<=mid)T[k].ls=build(l,mid);
if (mid<r)T[k].rs=build(mid+,r);
return k;
}
int insert(int x,int l,int r,int s,int kk)
{
now++;
if (l==r)
{
T[now].num=T[x].num+kk;
return now;
}
int k=now,mid=(l+r)/;
if (s<=mid)
{
T[k].ls=insert(T[x].ls,l,mid,s,kk);
T[k].rs=T[x].rs;
}
else
{
T[k].ls=T[x].ls;
T[k].rs=insert(T[x].rs,mid+,r,s,kk);
}
T[k].num=T[T[k].ls].num+T[T[k].rs].num;
return k;
}
ll find(int s,int x,int y,int l,int r)
{
if (l>y||r<x)return ;
if (x<=l&&y>=r)return T[s].num;
ll ans=;
int mid=(l+r)/;
if (x<=mid)ans+=find(T[s].ls,x,y,l,mid);
if (y>mid)ans+=find(T[s].rs,x,y,mid+,r);
return ans;
}
int main()
{
int cas;
scanf("%d",&cas);
while (cas--)
{
scanf("%d",&n);
memset(T,,sizeof T);
memset(la,,sizeof la);
cnt=now=;
for (int i=;i<=n;i++)scanf("%d",&a[i]);
scanf("%d",&m);
rt[]=build(,n);
for (int i=;i<=n;i++)
{
if (!la[a[i]])rt[i]=insert(rt[i-],,n,,a[i]);
else rt[i]=insert(rt[i-],,n,la[a[i]],a[i]);
la[a[i]]=i;
}
while (m--)
{
scanf("%d%d",&x,&y);
printf("%lld\n",find(rt[y],,x-,,n)-find(rt[x-],,x-,,n));
}
}
return ;
}

相关文章