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

来源:互联网 发布:靠谱韩代 淘宝店 良心 编辑:程序博客网 时间:2024/05/01 09:42

传送门:【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 ;}


0 0
原创粉丝点击