Description
After inventing Turing Tree, 3xian always felt boring when solving problems about intervals, because Turing Tree could easily have the solution. As well, wily 3xian made lots of new problems about intervals. So, today, this sick thing happens again...
Now given a sequence of N numbers A1, A2, ..., AN and a number of Queries(i, j) (1≤i≤j≤N). For each Query(i, j), you are to caculate the sum of distinct values in the subsequence Ai, Ai+1, ..., Aj.
Input
The first line is an integer T (1 ≤ T ≤ 10), indecating the number of testcases below.
For each case, the input format will be like this:
- Line 1: N (1 ≤ N ≤ 30,000).
- Line 2: N integers A1, A2, ..., AN (0 ≤ Ai ≤ 1,000,000,000).
- Line 3: Q (1 ≤ Q ≤ 100,000), the number of Queries.
- Next Q lines: each line contains 2 integers i, j representing a Query (1 ≤ i ≤ j ≤ N).
Output
For each Query, print the sum of distinct values of the specified subsequence in one line.
Sample Input
2
3
1 1 4
2
1 2
2 3
5
1 1 2 1 3
3
1 5
2 4
3 5
Sample Output
1
5
6
3
6
题目大意:
线段树的区间查询,查询区间内不同数值的数的和。
核心思想:
将数值离散化后记录每个数值a[i]最近一次出现的位置pre[a[i]]。
将查询离线处理,按查询区间的右端点排序,遍历原数组,依次进树,每进入一个数a[i],就将位置pre[a[i]]上的数清零,并更新pre[a[i]]=i。
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=3e4+20,Q=1e5+20;
ll a[N],b[N];
int pre[N],cnt;
struct tnode{
int l,r,id;
ll chu;
}que[Q];
struct node{
int l,r;
ll sum;
}tr[N<<2];
void pushup(int m)
{
tr[m].sum=tr[m<<1].sum+tr[m<<1|1].sum;
return;
}
void build(int m,int l,int r)
{
tr[m].l=l;
tr[m].r=r;
if(l==r)
{
tr[m].sum=0;
return;
}
int mid=(l+r)>>1;
build(m<<1,l,mid);
build(m<<1|1,mid+1,r);
pushup(m);
return;
}
void update(int m,int x,ll v)
{
if(tr[m].l==x&&tr[m].r==x)
{
tr[m].sum=v;
return;
}
int mid=(tr[m].l+tr[m].r)>>1;
if(x<=mid)
update(m<<1,x,v);
else
update(m<<1|1,x,v);
pushup(m);
return;
}
ll query(int m,int l,int r)
{
if(tr[m].l==l&&tr[m].r==r)
return tr[m].sum;
int mid=(tr[m].l+tr[m].r)>>1;
if(r<=mid)
return query(m<<1,l,r);
if(l>mid)
return query(m<<1|1,l,r);
return query(m<<1,l,mid)+query(m<<1|1,mid+1,r);
}
bool cmp1(tnode x,tnode y)
{
return x.r<y.r;
}
bool cmp2(tnode x,tnode y)
{
return x.id<y.id;
}
int getid(ll x)
{
return lower_bound(b+1,b+cnt,x)-b;
}
int main()
{
int T;
cin>>T;
while(T--)
{
int n,q;
cnt=1;
//输入
scanf("%d",&n);
for(int i=1;i<=n;i++)
pre[i]=0;
a[0]=-1;
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
//离散化
sort(a+1,a+1+n);
for(int i=1;i<=n;i++)
if(a[i]!=a[i-1])
b[cnt++]=a[i];
//建树
build(1,1,n);
//离线处理
scanf("%d",&q);
for(int i=1;i<=q;i++)
{
scanf("%d%d",&que[i].l,&que[i].r);
que[i].id=i;
}
sort(que+1,que+1+q,cmp1);
que[0].r=0;
//更新和查询同时进行
for(int i=1;i<=q;i++)
{
for(int j=que[i-1].r+1;j<=que[i].r;j++)
{
int z=getid(a[j]);
if(pre[z])
update(1,pre[z],0);
update(1,j,a[j]);
pre[z]=j;
}
que[i].chu=query(1,que[i].l,que[i].r);
}
sort(que+1,que+1+q,cmp2);
//输出
for(int i=1;i<=q;i++)
printf("%lld
",que[i].chu);
}
return 0;
}