您的位置:首页 > 其它

BZOJ 1878: [SDOI2009]HH的项链( BIT )

2015-05-30 21:51 441 查看


离线处理 , 记下询问的左右端点并排序 , 然后可以利用树状数组 , 保证查询区间时每种颜色只计算一次

------------------------------------------------------------------------------------------------

#include<cstdio>#include<algorithm>#include<cstring>#include<iostream> #define rep( i , n ) for( int i = 0 ; i < n ; ++i )#define clr( x , c ) memset( x , c , sizeof( x ) )#define lowbit( x ) (x & -x)#define Rep( i , n ) for( int i = 1 ; i <= n ; ++i ) using namespace std; const int maxn = 50000 + 5;const int maxq = 200000 + 5;const int MAXN = 1000000 +5; int b[ maxn ];int n; inline void add( int x ) {

if( ! x ) return; for( ; x <= n ; x += lowbit( x ) ) b[ x ] += 1;} inline int sum( int x ) { int ans = 0; for( ; x > 0 ; x -= lowbit( x ) ) ans += b[ x ]; return ans;} int next[ MAXN ];int last[ MAXN ];int x[ maxn ]; struct Q { int l , r; int x; inline void Read( int _x ) { scanf( "%d%d" , &l , &r ); x = _x; } bool operator < ( const Q &rhs ) const { return l < rhs.l; }}; Q q[ maxq ];int ans[ maxq ]; int main() { freopen( "test.in" , "r" , stdin ); clr( b , 0 ); clr( last , -1 ); clr( next , 0 ); cin >> n; Rep( i , n ) { scanf( "%d" , &x[ i ] ); if( last[ x[ i ] ] != -1 ) next[ last[ x[ i ] ] ] = i; else add( i ); last[ x[ i ] ] = i; } int m; cin >> m; rep( i , m ) q[ i ].Read( i ); sort( q , q + m ); int s = 1; rep( i , m ) { while( s < q[ i ].l ) { add( next[ s ] ); s++; } ans[ q[ i ].x ]= sum( q[ i ] .r ) - sum( q[ i ].l - 1 ); } rep( i , m ) printf( "%d\n" , ans[ i ] ); return 0;}------------------------------------------------------------------------------------------------

1878: [SDOI2009]HH的项链

Time Limit: 4 Sec Memory Limit: 64 MB
Submit: 2117 Solved: 1043
[Submit][Status][Discuss]

Description

HH有一串由各种漂亮的贝壳组成的项链。HH相信不同的贝壳会带来好运,所以每次散步 完后,他都会随意取出一段贝壳,思考它们所表达的含义。HH不断地收集新的贝壳,因此, 他的项链变得越来越长。有一天,他突然提出了一个问题:某一段贝壳中,包含了多少种不同 的贝壳?这个问题很难回答。。。因为项链实在是太长了。于是,他只好求助睿智的你,来解 决这个问题。

Input

第一行:一个整数N,表示项链的长度。 第二行:N个整数,表示依次表示项链中贝壳的编号(编号为0到1000000之间的整数)。 第三行:一个整数M,表示HH询问的个数。 接下来M行:每行两个整数,L和R(1 ≤ L ≤ R ≤ N),表示询问的区间。

Output

M行,每行一个整数,依次表示询问对应的答案。

Sample Input

6
1 2 3 4 3 5
3
1 2
3 5
2 6

Sample Output

2
2
4

HINT

对于20%的数据,N ≤ 100,M ≤ 1000;
对于40%的数据,N ≤ 3000,M ≤ 200000;
对于100%的数据,N ≤ 50000,M ≤ 200000。

Source

Day2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: