| ||||||||||
Turing TreeTime Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3481 Accepted Submission(s): 1155
Problem 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
Sample Output
Author
3xian@GDUT
|
题意:给定一个区间,查询这个区间上不同的数的和
3xian大神的题。。。
首先我们把所有查询区间记录下来,然后按照区间的右值排序,接着从左到右把每一个数更新到线段树中,并记录它出现的位置。如果一个数已经出现过,那么我们就把他上次出现的位置的值置为0,并更新它出现的位置。因为我们的查询区间是按右值排序的,因此把过去重复出现的数字置为0不会影响结果。当更新到某个区间的右值时,我们就查询一次该区间的答案,并把答案记下来。最后把区间查询的答案按照输入顺序输出即可。这样复杂度就成了nlogn。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=30010;
typedef long long LL;
int n,m;
int a[maxn];
map<int,int> vis;
struct Q
{
int l,r;
int id;
bool operator < (const Q & a)const
{
return r<a.r;
}
}q[100100];
LL ans[100100];
struct IntervalTree
{
LL sum[maxn<<3];
void build(){memset(sum,0,sizeof(sum));}
void update(int o,int l,int r,int pos,int val)
{
if(l==r)
{
sum[o]+=val;
return;
}
int mid=(l+r)>>1;
if(pos<=mid)update(o<<1,l,mid,pos,val);
else update(o<<1|1,mid+1,r,pos,val);
sum[o]=sum[o<<1]+sum[o<<1|1];
}
LL query(int o,int l,int r,int q1,int q2)
{
if(q1<=l&&r<=q2)return sum[o];
int mid=(l+r)>>1;
LL ans=0;
if(q1<=mid)ans+=query(o<<1,l,mid,q1,q2);
if(q2>mid)ans+=query(o<<1|1,mid+1,r,q1,q2);
return ans;
}
}tree;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d",&q[i].l,&q[i].r);
q[i].id=i;
}
sort(q+1,q+1+m);
vis.clear();
tree.build();
int cur=1;
for(int i=1;i<=m;i++)
{
for(;cur<=n&&cur<=q[i].r;cur++)
{
if(vis[a[cur]])tree.update(1,1,n,vis[a[cur]],-a[cur]);
tree.update(1,1,n,cur,a[cur]);
vis[a[cur]]=cur;
}
ans[q[i].id]=tree.query(1,1,n,q[i].l,q[i].r);
}
for(int i=1;i<=m;i++)printf("%I64d\n",ans[i]);
}
return 0;
}