题目:
洛谷 P1903
分析:很显然的待修改的莫队。第一次打,感觉有点丑。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
const int maxn=10005;
const int tot_color=1e6+2;
using namespace std;
struct node{
int id,l,r,x,ans;
//id表示询问位置,l,r表示询问系数,x表示前面有多少个修改,ans表示答案
}q[maxn];
struct te{
int x,col,pre;
//x表示修改的地址,col表示修改后颜色,pre表示修改前颜色
}c[maxn];
int n,m,i,ans,l,r,cnt,block,change,x,y;
int a[maxn],sum[tot_color],belong[maxn];
bool cmp(node x,node y)
{
if (belong[x.l]==belong[y.l])
{
if (belong[x.r]==belong[y.r]) return x.x<y.x;
return x.r<y.r;
}
return x.l<y.l;
}
void updata(int x,int c)
{
if (c==1)
{
if (sum[a[x]]==0) ans++;
sum[a[x]]++;
}
else
{
sum[a[x]]--;
if (sum[a[x]]==0) ans--;
}
}
void updata1(int x,int c)
{
if ((x<q[i].l) || (x>q[i].r)) return;
if (c==1)
{
if (sum[a[x]]==0) ans++;
sum[a[x]]++;
}
else
{
sum[a[x]]--;
if (sum[a[x]]==0) ans--;
}
}
bool cmp1(node x,node y)
{
return x.id<y.id;
}
int main()
{
scanf("%d%d",&n,&m);
for (i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
char op[1];
for (i=1;i<=m;i++)
{
scanf("%s",op);
scanf("%d%d",&x,&y);
if (op[0]=='R')
{
change++;
c[change].x=x;
c[change].col=y;
}
else
{
cnt++;
q[cnt].id=i;
q[cnt].l=x;
q[cnt].r=y;
q[cnt].x=change;
}
}
block=trunc(sqrt(n));
for (i=1;i<=n;i++) belong[i]=(i-1)/block+1;
sort(q+1,q+1+cnt,cmp);
l=r=1;
ans=1;
change=0;
sum[a[1]]++;
for (i=1;i<=cnt;i++)
{
for (r;r<q[i].r;r++) updata(r+1,1);
for (r;r>q[i].r;r--) updata(r,0);
for (l;l<q[i].l;l++) updata(l,0);
for (l;l>q[i].l;l--) updata(l-1,1);
for (change;change<q[i].x;change++)
{
updata1(c[change+1].x,0);
c[change+1].pre=a[c[change+1].x];
a[c[change+1].x]=c[change+1].col;
updata1(c[change+1].x,1);
}
for (change;change>q[i].x;change--)
{
updata1(c[change].x,0);
a[c[change].x]=c[change].pre;
updata1(c[change].x,1);
}
q[i].ans=ans;
}
sort(q+1,q+1+cnt,cmp1);
for (i=1;i<=cnt;i++)
{
printf("%d\n",q[i].ans);
}
}