【COGS】421 [SDOI2009] HH的项链 树状数组

传送门:【COGS】421 [SDOI2009] HH的项链


题目分析:将区间以右端点为关键字降序排序,然后从左到右依次遍历每个数并插入到树状数组中,如果遍历到一个数的时候在他的前面已经有一个相同的数时,将之前位置上的数从树状数组中删除。然后我们每处理完一个位置上的数后,看这个位置上是否有右端点,如果有则做一次求和,这个右端点属于的区间【L,R】的值即sum(R)-sum(L-1)。


代码如下:


#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std ;
 
#define REP( i , a , b ) for ( int i = ( a ) ; i <  ( b ) ; ++ i )
#define FOR( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i )
#define REV( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i )
#define travel( e , H , u ) for ( Edge* e = H[u] ; e ; e = e -> next )
#define CLR( a , x ) memset ( a , x , sizeof a )
#define CPY( a , x ) memcpy ( a , x , sizeof a )
#define ls ( o << 1 )
#define rs ( o << 1 | 1 )
#define lson ls , l , m
#define rson rs , m + 1 , r
#define root 1 , 1 , n
#define mid ( ( l + r ) >> 1 )

const int MAXN = 50005 ;
const int MAXE = 200005 ;
const int MAXM = 1000005 ;

struct Edge {
	int v , idx ;
	Edge* next ;
} E[MAXE] , *H[MAXN] , *cur ;

int pre[MAXM] ;
int num[MAXN] ;
int ans[MAXE] ;
int T[MAXN] ;
int n , q ;

void scanf ( int& x , char c = 0 ) {
	while ( ( c = getchar () ) < '0' || c > '9' ) ;
	x = c - '0' ;
	while ( ( c = getchar () ) >= '0' && c <= '9' ) x = x * 10 + c - '0' ;
}

void clear () {
	cur = E ;
	CLR ( H , 0 ) ;
}

void addedge ( int u , int v , int idx ) {
	cur -> v = v ;
	cur -> idx = idx ;
	cur -> next = H[u] ;
	H[u] = cur ++ ;
}
void modify ( int x , int v ) {
	while ( x <= n ) {
		T[x] += v ;
		x += x & -x ;
	}
}

int sum ( int x , int ans = 0 ) {
	while ( x ) {
		ans += T[x] ;
		x -= x & -x ;
	}
	return ans ;
}

void solve () {
	int R , L ;
	clear () ;
	CLR ( T , 0 ) ;
	CLR ( pre , 0 ) ;
	FOR ( i , 1 , n ) scanf ( num[i] ) ;
	scanf ( q ) ;
	REP ( i , 0 , q ) {
		scanf ( L ) ; scanf ( R ) ;
		addedge ( R , L , i ) ;
	}
	FOR ( i , 1 , n ) {
		if ( pre[num[i]] ) modify ( pre[num[i]] , -1 ) ;
		pre[num[i]] = i ;
		modify ( i , 1 ) ;
		travel ( e , H , i ) ans[e -> idx] = sum ( i ) - sum ( e -> v - 1 ) ;
	}
	REP ( i , 0 , q ) printf ( "%d\n" , ans[i] ) ;
}

int main () {
	freopen ( "diff.in" , "r" , stdin ) ;
	freopen ( "diff.out" , "w" , stdout ) ;
	scanf ( n ) ;
	solve () ;
	return 0 ;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值