HDU 3333 Turing Tree(離線線段樹),hduturing
Problem DescriptionAfter 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.
InputThe 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).
OutputFor 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
15636
題意:求給定區間內不同值的和,重複的計算一次。。詢問Q<=100000,考慮離線做法。將所有的詢問儲存下來,按照右端點由小到大排序。跟新小於p[i].r的值,對值進行hash,儲存值的位置,相同時,原位置上值更新為0,此值的位置更新的當前位置。。
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<map>typedef long long LL;using namespace std;#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )#define CLEAR( a , x ) memset ( a , x , sizeof a )const int maxn=30005;const int maxm=100005;LL sum[maxn<<2],a[maxn],ans[maxm];struct node{ int l,r,index; bool operator<(const node a)const { return r<a.r; }}p[maxm];//儲存每次詢問map<LL,int>hash;int t,n,m;void pushup(int rs){ sum[rs]=sum[rs<<1]+sum[rs<<1|1];}void build(int rs,int l,int r){ sum[rs]=0; if(l==r) return ; int mid=(l+r)>>1; build(rs<<1,l,mid); build(rs<<1|1,mid+1,r);}void update(int rs,LL c,int x,int l,int r){ if(l==r) { sum[rs]=c; return ; } int mid=(l+r)>>1; if(x<=mid) update(rs<<1,c,x,l,mid); else update(rs<<1|1,c,x,mid+1,r); pushup(rs);}LL query(int rs,int x,int y,int l,int r){ if(l>=x&&r<=y) return sum[rs]; int mid=(l+r)>>1; LL res=0; if(x<=mid) res+=query(rs<<1,x,y,l,mid); if(y>mid) res+=query(rs<<1|1,x,y,mid+1,r); return res;}void solve(){ int pos=1; REPF(i,1,m) { while(p[i].r>=pos) { if(hash[a[pos]])//若此值出現過,原位置上值更新為0. update(1,0,hash[a[pos]],1,n); hash[a[pos]]=pos;//更新當前值的位置 update(1,a[pos],pos,1,n);pos++; }// cout<<"666 "<<query(1,1,2,1,n)<<endl; ans[p[i].index]=query(1,p[i].l,p[i].r,1,n); }}int main(){ scanf("%d",&t); int x,y; while(t--) { hash.clear(); scanf("%d",&n); build(1,1,n); REPF(i,1,n) scanf("%I64d",&a[i]); scanf("%d",&m); REPF(i,1,m) { scanf("%d%d",&p[i].l,&p[i].r); p[i].index=i; } sort(p+1,p+1+m); solve(); REPF(i,1,m) printf("%I64d\n",ans[i]); } return 0;}