【SPOJ - DQUERY】【D-query】

EnglishVietnamese

Given a sequence of n numbers a1, a2, ..., an and a number of d-queries. A d-query is a pair (i, j) (1 ≤ i ≤ j ≤ n). For each d-query (i, j), you have to return the number of distinct elements in the subsequence ai, ai+1, ..., aj.

Input

  • Line 1: n (1 ≤ n ≤ 30000).
  • Line 2: n numbers a1, a2, ..., an (1 ≤ ai ≤ 106).
  • Line 3: q (1 ≤ q ≤ 200000), the number of d-queries.
  • In the next q lines, each line contains 2 numbers i, j representing a d-query (1 ≤ i ≤ j ≤ n).

Output

  • For each d-query (i, j), print the number of distinct elements in the subsequence ai, ai+1, ..., aj in a single line.

     

Example

Input
5
1 1 2 1 3
3
1 5
2 4
3 5

Output
3
2
3 

乍一看,这道题和前边的那道计算某个区间内的不同数字的和 的那道题很是相似,但是用的却不一样了,这道题目求解是某个区间内不同数字的个数,用的是主席树,这个东西我不会啊,百度脑部,然后又参考的题解

ac代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#define maxn 100000
using namespace std;

int n,q;
int cnt=0;
struct node{
	int l,r;
	int sum;
}p[maxn*40];

int la[maxn*10];
int a[maxn];
int root[maxn];

int build(int l,int r)
{
	int nc=++cnt;
	p[nc].sum=0;
	p[nc].l=p[nc].r=0;
	if(l==r)
		return nc;
	int m=(l+r)>>1;
	p[nc].l=build(l,m);
	p[nc].r=build(m+1,r);
	return nc;
}

int updata(int pos,int c,int v,int l,int r)
{
	int nc=++cnt;
	p[nc]=p[c];
	p[nc].sum+=v;
	if(l==r) return nc;
	int m=(l+r)>>1;
	if(m>=pos) 
		p[nc].l=updata(pos,p[c].l,v,l,m);
	else
		p[nc].r=updata(pos,p[c].r,v,m+1,r);
	return nc; 
}
int query(int pos,int c,int l,int r)
{
	if(l==r) return p[c].sum;
	int m=(l+r)>>1;
	if(m>=pos) 
		return p[p[c].r].sum+query(pos,p[c].l,l,m);
	else
		return query(pos,p[c].r,m+1,r);
}

int main()
{
	scanf("%d",&n);
	memset(la,-1,sizeof(la));
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
	root[0]=build(1,n);
	for(int i=1;i<=n;i++)
	{
		int v=a[i];
		if(la[v]==-1)
		{
			root[i]=updata(i,root[i-1],1,1,n);
		}
		else
		{
			int t=updata(la[v],root[i-1],-1,1,n);
			root[i]=updata(i,t,1,1,n);
		}
		la[v]=i;
	}
	scanf("%d",&q);
	while(q--)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		printf("%d\n",query(x,root[y],1,n));
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值