蒟蒻怎么 5min 就出思路了啊 /jy
感觉莫队的题都差不太多。
可以使用类似数颜色不带修的做法处理出现次数 的数。
然后把 add 和 del 的代码改一下。(我的代码是二合一的)
这是数颜色(出现次数 )的。
inline void update(int x,int d){//d=1 是 add,d=-1 是 del
if(d==1) Ans+=(cnt[x]==0),cnt[x]++;
else cnt[x]--,Ans-=(cnt[x]==0);
}然后改成出现次数 的。
inline void update(int x,int d){
if(d==1) Ans+=(cnt[x]==1),cnt[x]++;
else cnt[x]--,Ans-=(cnt[x]==1);
}最后把答案减去 的。
inline void update(int x,int d){
if(d==1) Ans+=(cnt[x]==1)-(cnt[x]==2),cnt[x]++;
else cnt[x]--,Ans-=(cnt[x]==1)-(cnt[x]==2);
}然后呢?没了,这题就是这么简单。 代码:
#include<bits/stdc++.h>
#define int long long
#define x first
#define y second
#define rep(i,l,r) for(int i=l;i<=r;i++)
using namespace std;
constexpr int N=1000005;
int n,m,k,blen,cnt[N],a[N],ans[N],Ans;
struct query{int l,r,id;}q[N];
inline void update(int x,int d){
if(d==1) Ans+=(cnt[x]==1)-(cnt[x]==2),cnt[x]++;
else cnt[x]--,Ans-=(cnt[x]==1)-(cnt[x]==2);
}
signed main(){
cin.tie(0)->sync_with_stdio(0);
cin>>n>>m;
rep(i,1,n) cin>>a[i];
int qcnt=0;
rep(i,1,m){
int l,r;
cin>>l>>r;
q[i]={l,r,i};
}
blen=sqrt(n);
sort(q+1,q+m+1,[&](query a,query b){
if(a.l/blen!=b.l/blen) return a.l/blen<b.l/blen;
return (a.l/blen)&1?a.r<b.r:a.r>b.r;
});//写了个没啥用的优化
int l=1,r=0;
rep(i,1,m){
while(l<q[i].l) update(a[l++],-1);
while(l>q[i].l) update(a[--l],1);
while(r<q[i].r) update(a[++r],1);
while(r>q[i].r) update(a[r--],-1);
ans[q[i].id]=Ans;
}
rep(i,1,m) cout<<ans[i]<<"\n";
}鲜花:这题不需要离散化。建议加强数据。