hdu3333-Turing Tree 线段树+离散化

来源:互联网 发布:Js 中isinfinite 编辑:程序博客网 时间:2024/05/29 19:15

Turing Tree

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5338    Accepted Submission(s): 1885


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
231 1 421 22 351 1 2 1 331 52 43 5
 

Sample Output
1563

6

题意:给你一个序列的数,询问区间内不同数的和

解题思路:需要使用离散化处理,相同的值去重,排序,求和

ac代码:

#include<cstdio>#include<cstring>#include<map>#include<algorithm>using namespace std;#define MAXN 33333 struct Query{int i,l,r;bool operator<(const Query &q) const{return r<q.r;}}que[111111]; long long tree[MAXN<<2];int N,x,y;void update(int i,int j,int k){if(i==j){tree[k]+=y;return;}int mid=i+j>>1;if(x<=mid) update(i,mid,k<<1);else update(mid+1,j,k<<1|1);tree[k]=tree[k<<1]+tree[k<<1|1];}long long query(int i,int j,int k){if(x<=i && j<=y) return tree[k];int mid=i+j>>1;long long ret=0;if(x<=mid) ret+=query(i,mid,k<<1);if(y>mid) ret+=query(mid+1,j,k<<1|1);return ret;} int a[MAXN];long long ans[111111];int main(){int t,n,m;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=0; i<m; ++i){scanf("%d%d",&que[i].l,&que[i].r);que[i].i=i;}sort(que,que+m);map<int,int> posi;memset(tree,0,sizeof(tree));for(N=1; N<n; N<<=1);int p=0;for(int i=0; i<m; ++i){while(p<que[i].r){++p;if(posi.count(a[p])){x=posi[a[p]]; y=-a[p];update(1,N,1);}x=p; y=a[p];update(1,N,1);posi[a[p]]=p;}x=que[i].l; y=que[i].r;ans[que[i].i]=query(1,N,1);}for(int i=0; i<m; ++i){printf("%lld\n",ans[i]);}}return 0;}

点击打开链接http://acm.hdu.edu.cn/showproblem.php?pid=3333