您的位置:首页 > 其它

HDU 3333 Turing Tree (离线线段树,经典)

2017-07-13 11:54 465 查看
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

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

题意:多次查询区间中不同数之和

分析:所有询问右端点排序后,从小到大扫过去,线段树维护序列区间和,用一个map记录各个数最右边出现的位置,一遇到一个数就把之前位置消除并更新当前位置,相当于把各个数尽量向右移动。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <queue>
#define mem(p,k) memset(p,k,sizeof(p));
#define rep(a,b,c) for(int a=b;a<c;a++)
#define pb push_back
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define inf 0x6fffffff
#define ll long long
using namespace std;
const int maxn=30005;
struct que{
int l,r,i;
bool operator <(que a){
return r<a.r;
}
}que[100010];
int n,q;
ll a[maxn];
ll sum[maxn<<2],ans[100010];
map<ll,int> pos;
void update(int k,int val,int l,int r,int rt){
sum[rt]+=val;
if(l==r)return;
int m=(l+r)>>1;
if(k<=m)update(k,val,lson);
else update(k,val,rson);
}
ll query(int L,int R,int l,int r,int rt){
if(L<=l && r<=R){
return sum[rt];
}
int m=(l+r)>>1;
ll ans=0;
if(m>=L) ans+=query(L,R,lson);
if(m<R) ans+=query(L,R,rson);
return ans;

}
int main()
{
int t;
cin>>t;
while(t--){
mem(sum,0);
int n,k=1;
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%lld",a+i);
scanf("%d",&q);
for(int i=1;i<=q;i++)scanf("%d%d",&que[i].l,&que[i].r),que[i].i=i;
sort(que+1,que+q+1);
pos.clear();
for(int i=1;i<=n;i++){
if(pos.count(a[i])){
update(pos[a[i]],-a[i],1,n,1);
}
pos[a[i]]=i;
update(i,a[i],1,n,1);
while(k<=q && i==que[k].r){
ans[que[k].i]=query(que[k].l,que[k].r,1,n,1);
//cout<<que[k].l<<que[k].r<<"=="<<ans[que[k].i]<<endl;
k++;
}
}
for(int i=1;i<=q;i++){
printf("%lld\n",ans[i]);
}

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: