Spoj 3267 DQUERY - D-query

题目描述

English VietnameseGiven a sequence of n numbers a _{1}1 , a _{2}2 , ..., a _{n}n 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 a _{i}i , a _{i+1}i+1 , ..., a _{j}j.

输入输出格式

输入格式:

 

  • Line 1: n (1 ≤ n ≤ 30000).
  • Line 2: n numbers a _{1}1 , a _{2}2 , ..., a _{n}n (1 ≤ a _{i}i ≤ 10 ^{6}6 ).
  • 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).

 

输出格式:

 

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

 

输入输出样例

输入样例#1: 
5
1 1 2 1 3
3
1 5
2 4
3 5
输出样例#1: 
3
2
3


离线扫描经典题,但是我复习一下主席树233

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=200005;
struct node{
	int tag;
	node *lc,*rc;
}nil[maxn*53],*rot[30005],*cnt;
int n,Q,a[30005],le,ri,pre[maxn*5];

node *update(node *u,int l,int r){
	node *ret=++cnt;
	*ret=*u;
	if(l>=le&&r<=ri){
		ret->tag++;
		return ret;
	}
	
	int mid=l+r>>1;
	if(le<=mid) ret->lc=update(ret->lc,l,mid);
	if(ri>mid) ret->rc=update(ret->rc,mid+1,r);
	
	return ret;
}

int query(node *u,int l,int r){
	if(l==r) return u->tag;
	int mid=l+r>>1;
	if(le<=mid) return u->tag+query(u->lc,l,mid);
	else return u->tag+query(u->rc,mid+1,r);
}

inline void init(){
	rot[0]=nil->lc=nil->rc=cnt=nil;
	nil->tag=0;
	for(int i=1;i<=n;i++){
		le=pre[a[i]]+1,ri=i,rot[i]=update(rot[i-1],1,1000000);
		pre[a[i]]=i;
	}
}

inline void solve(){
	scanf("%d",&Q);
	while(Q--){
		scanf("%d%d",&le,&ri);
		printf("%d\n",query(rot[ri],1,1000000));
	}
}

int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",a+i);
	init();
	solve();
	return 0;
}

  


posted @ 2018-04-01 14:44  蒟蒻JHY  阅读(337)  评论(0编辑  收藏  举报