代码如下:
# include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2e7+10;
int c[N],id[N];
char opt[N][10];
struct node{
int l,r,id,pre;
}a[N];
struct nodeP{
int pos,val;
}b[N];
int cnt[N];
int res[N];
bool cmp(node x,node y)
{
if(id[x.l] == id[y.l]) return x.l < y.l;
else
{
if(id[x.r] == id[y.r]) return x.pre < y.pre;
else
{
if(id[x.l]&1) return x.r > y.r;
else x.r < y.r;
}
}
}
int ans;
void add(int x)
{
cnt[x]++;
if(cnt[x] == 1) ans++;
}
void del(int x)
{
cnt[x]--;
if(cnt[x] == 0) ans--;
}
void update(int now,int i)
{
if(b[now].pos >= a[i].l && b[now].pos <= a[i].r)
{
if(--cnt[c[b[now].pos]] == 0) ans--;
if(++cnt[b[now].val] == 1) ans++;
}
swap(c[b[now].pos],b[now].val);
}
signed main (){
int n,q;
scanf("%lld%lld",&n,&q);
int len = pow(n,0.666);
for(int i = 1;i <= n;i++)
{
scanf("%lld",&c[i]);
id[i] = (i-1)/len+1;
}
int cnt1 = 0,cnt2 = 0;
for(int i = 1;i <= q;i++)
{
scanf("%s",opt[i]);
int x,y;
scanf("%lld%lld",&x,&y);
if(opt[i][0] == 'Q')
{
a[++cnt1].l = x;
a[cnt1].r = y;
a[cnt1].id = i;
a[cnt1].pre = cnt2;
}
else
{
// idx[i] = 1;
b[++cnt2].pos = x;
b[cnt2].val = y;
}
}
sort(a+1,a+q+1,cmp);
int l = 1,r = 0,now = 0;
for(int i = 1;i <= q;++i)
{
while(l > a[i].l) add(c[--l]);
while(r < a[i].r) add(c[++r]);
while(l < a[i].l) del(c[l++]);
while(r > a[i].r) del(c[r--]);
while(now < a[i].pre) update(++now,i);
while(now > a[i].pre) update(now--,i);
res[a[i].id] = ans;
}
for(int i = 1;i <= q;i++)
{
if(opt[i][0] == 'Q')printf("%lld\n",res[i]);
}
return 0;
}
TLE #7~12,求助大佬。