hdu3333 Turing Tree(离线处理)(树状数组)

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
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
ll ans[1500009];
ll c[1500009];
int a[1500009];
ll b[1000009];
int has[1500009];
int hash[1500009];
int n,m;

struct sm{
	int l,r;
	int id;
}q[150009];

bool cmp(sm a,sm b){
	return a.r<b.r;
}

void add(int x,int num){
	for(;x<=n;x+=x&-x) c[x]+=num;
}

ll ask(int x){
	ll ans=0;
	for(;x;x-=x&-x) ans+=c[x];
	return ans; 
}

int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		memset(c,0,sizeof(c));
		memset(has,0,sizeof(has));
		scanf("%d",&n);
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
			b[i]=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;
		}
		int ne=1;
		sort(b+1,b+1+n);
		sort(q+1,q+1+m,cmp);
		for(int i=1;i<=n;i++){
			int pos=lower_bound(b+1,b+1+n,a[i])-b;
			if(has[pos]==0){
				add(i,a[i]);
				has[pos]=i;
			}
			else{
				add(has[pos],-a[i]);
				has[pos]=i;
				add(i,a[i]);
			}
			while(q[ne].r==i&&ne<=m){
				ans[q[ne].id]=ask(i)-ask(q[ne].l-1);
				ne++;
			}
		}
		for(int i=1;i<=m;i++){
			printf("%lld\n",ans[i]);
		}
	}
}

你可能感兴趣的:(模板,线段树)