带修莫队,即支持修改的莫队。
前置知识:莫队。
容易发现,不带修改操作,这题就是莫队板子。
但是它带有修改。
解决方法:
- 分开保存查询和修改。对于每个查询,我们记录一个值 ,表示目前是第 次修改。
- 排序有三维,先左端点,然后是右端点,最后是时间端点 。
- 对于每次修改,先将它移到对应的左端点和右端点,接着暴力移到目前时间 即可。
#include <bits/stdc++.h>
using namespace std;
inline int Read() {
int x = 0 , f = 1;
char c = getchar();
for( ; c < '0' || c > '9' ; c = getchar() ) f ^= ( c == '-' );
for( ; c >= '0' && c <= '9' ; c = getchar() ) x = ( x << 3 ) + ( x << 1 ) + ( c ^ 48 );
return f ? x : -x;
}
char GetC() {
char c = getchar();
for( ; c != 'Q' && c != 'R' ; c = getchar() );
return c;
}
const int _ = 133335 , __ = 1e6 + 5;
struct Que {
int l , r , t , id; //t是时间节点,id是询问编号,方便直接放进ans数组里面
} que[_];
struct Cha {
int pos , col;
} cha[_];
int qnum , cnum;
int a[_] , cnt[__] , blo[_] , ans[_];
int n , m , now , CurrentL , CurrentR , res;
int Cmp( Que x , Que y ) {
if( blo[ x.l ] != blo[ y.l ] ) return x.l < y.l;
if( blo[ x.r ] != blo[ y.r ] ) return x.r < y.r;
return x.t < y.t;
}
void Add( int x ) {
if( cnt[ a[ x ] ] == 0 ) res++;
cnt[ a[ x ] ]++;
}
void Del( int x ) {
if( cnt[ a[ x ] ] == 1 ) res--;
cnt[ a[ x ] ]--;
}
void Change( int x ) {
if( cha[ x ].pos >= CurrentL && cha[ x ].pos <= CurrentR ) { //如果在区间内,那就得更改cnt数组
cnt[ a[ cha[ x ].pos ] ]--;
if( cnt[ a[ cha[ x ].pos ] ] == 0 ) res--; //没有就要答案减1
if( cnt[ cha[ x ].col ] == 0 ) res++; //新的就要答案加1
cnt[ cha[ x ].col ]++;
}
swap( cha[ x ].col , a[ cha[ x ].pos ] ); //交换达到修改/还原
}
int main() {
n = Read() , m = Read();
int siz = pow( n , 2.0 / 3.0 ); //神奇数值跑得最快
for( int i = 1 ; i <= n ; i++ ) {
a[ i ] = Read();
blo[ i ] = i / siz + 1;
}
for( int i = 1 ; i <= m ; i++ ) {
char op = GetC();
int l = Read() , r = Read();
if( op == 'Q' ) que[ ++qnum ] = Que{ l , r , cnum , qnum };
else cha[ ++cnum ] = Cha{ l , r };
}
sort( que + 1 , que + 1 + qnum , Cmp );
for( int i = 1 ; i <= qnum ; i++ ) {
while( CurrentL < que[ i ].l ) Del( CurrentL++ );
while( CurrentL > que[ i ].l ) Add( --CurrentL );
while( CurrentR > que[ i ].r ) Del( CurrentR-- );
while( CurrentR < que[ i ].r ) Add( ++CurrentR );
while( now < que[ i ].t ) Change( ++now ); //暴力移动t
while( now > que[ i ].t ) Change( now-- );
ans[ que[ i ].id ] = res;
}
for( int i = 1 ; i <= qnum ; i++ ) printf( "%d\n" , ans[ i ] );
return 0;
}