【洛谷P1903】数颜色

题目大意:给定一个长度为 N 的序列,每个点有一个颜色。现给出 M 个操作,支持单点修改颜色和询问区间颜色数两个操作。

题解:学会了序列带修改的莫队。
莫队本身是不支持修改的。带修该莫队的本质也是对询问进行分块,不过在莫队转移时需要多维护一个时间维度,即:每个操作的相对顺序。具体来讲,将序列分成 (O(n^{1 over 3})) 块,每个块的大小是 (O(n^{2 over 3})),对询问的排序的优先级顺序是:询问左端点所在块,询问右端点所在块,询问的时间顺序。经过分析,带修该莫队的时间复杂度为 (O(n^{5 over 3})),具体分析方式和静态莫队类似。对排好序的询问进行按顺序处理,首先考虑时间维度,通过比较时间的先后,决定是顺序执行还是时间倒流,这可以通过记录一个 pre 变量来维护。

注意:在莫队中,对于 l 的初始化应该为 1,r 的初始化应该为 0,这是由询问转移的性质决定的。对于带修改莫队来说,时间维度也需要维护一个变量,表示当前的时间。时间的初始化应该为 0。

代码如下

#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define all(x) x.begin(),x.end()
#define cls(a,b) memset(a,b,sizeof(a))
#define debug(x) printf("x = %d
",x) 
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=5e4+10;
const int maxm=1e6+10;
const double eps=1e-6;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll sqr(ll x){return x*x;}
inline ll read(){
	ll x=0,f=1;char ch;
	do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
	do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
	return f*x;
}
/*--------------------------------------------------------*/

char s[4];
int n,m,l=1,r=0,cur=0,a[maxn],cnt[maxm],sum,ans[maxn];
struct query{int id,l,r,t,bl,br;}q[maxn];
struct node{int pos,val,pre,t;}mo[maxn];
int tot,tot1,tot2;
inline int get(int pos){return (pos-1)/tot+1;}
bool cmp(const query &x,const query &y){
	return x.bl!=y.bl?x.bl<y.bl:x.br!=y.br?x.br<y.br:x.t<y.t;
}

void read_and_parse(){
	n=read(),m=read(),tot=pow(n,0.6);
	for(int i=1;i<=n;i++)a[i]=read();
	for(int i=1;i<=m;i++){
		scanf("%s",s);
		if(s[0]=='Q')++tot1,q[tot1].id=tot1,q[tot1].t=i,q[tot1].l=read(),q[tot1].r=read(),q[tot1].bl=get(q[tot1].l),q[tot1].br=get(q[tot1].r);
		else ++tot2,mo[tot2].t=i,mo[tot2].pos=read(),mo[tot2].val=read();
	}
	sort(q+1,q+tot1+1,cmp);
}

inline void update(int x,int f){
	if(f==1){
		if(!cnt[a[x]])++sum;
		++cnt[a[x]];
	}else{
		--cnt[a[x]];
		if(!cnt[a[x]])--sum;
	}
}
void update2(int x,int f){
	if(mo[x].pos>=l&&mo[x].pos<=r){
		--cnt[a[mo[x].pos]];
		if(!cnt[a[mo[x].pos]])--sum;
	}
	if(f==1)mo[x].pre=a[mo[x].pos],a[mo[x].pos]=mo[x].val;
	else a[mo[x].pos]=mo[x].pre;
	if(mo[x].pos>=l&&mo[x].pos<=r){
		if(!cnt[a[mo[x].pos]])++sum;
		++cnt[a[mo[x].pos]];
	}
}
void change(int now){
	while(cur<tot2&&mo[cur+1].t<=now)update2(++cur,1);
	while(cur&&mo[cur].t>now)update2(cur--,-1);
}

void solve(){
	for(int i=1;i<=tot1;i++){
		change(q[i].t);
		while(r<q[i].r)update(++r,1);
		while(r>q[i].r)update(r--,-1);
		while(l>q[i].l)update(--l,1);
		while(l<q[i].l)update(l++,-1);
		ans[q[i].id]=sum;
	}
	for(int i=1;i<=tot1;i++)printf("%d
",ans[i]);
}

int main(){
	read_and_parse();
	solve();
	return 0;
}
原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10660622.html