HDU3333 Turing Tree(线段树)

题目

Source

http://acm.hdu.edu.cn/showproblem.php?pid=3333

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<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;
}

 

转载于:https://www.cnblogs.com/WABoss/p/5906579.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值