洛谷P3604(美好的每一天 莫队+状压
题意:
给一串字符串,多个区间询问,问多少个子区间的字母可以组成回文串
思路:
考虑只有1个奇数次出现的字母+一些偶数次字母或者全都是偶数次出现的字母才是合法的,子区间计数可以通过枚举+桶+类似hash的办法迅速记录。我们将字母出现次数转为二进制后,显然只有 ( 1 < < i ) (1<<i) (1<<i)或者全0的才能成功,我们通过枚举到当前字母插入或者删除的时候,通过维护前缀异或和记录,有贡献显然是 c n t [ a [ x ] ] cnt[a[x]] cnt[a[x]]和 c n t [ a [ x ] 异 或 ( 1 < < i ) ] ] cnt[a[x]异或(1<<i)]] cnt[a[x]异或(1<<i)]],注意初始 c n t [ 0 ] cnt[0] cnt[0]也有贡献
在使用莫队计数的时候,需要注意的是,由于维护的是 [ L , R ] [L,R] [L,R]区间,所以前缀异或和需要的是 [ L − 1 , R − 1 ] [L-1,R-1] [L−1,R−1]之间,所以L要减1,另外这题其实可以离散化预处理出每个数字能到达的状态,能减少常数,但我比较懒x
总时间复杂度 O ( 26 n m ) O(26n\sqrt m) O(26nm)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=6e4+5;
int n,m,big,pos[maxn],pl,pr,a[maxn],sum[maxn];
unsigned short cnt[(1<<26)+2];
ll ans=0;
char s[maxn];
struct Q{
int L,R,id;
bool operator<(const Q&a)const{
if(pos[L]!=pos[a.L])return pos[L]<pos[a.L];
if(pos[L]&1)return R>a.R;
return R<a.R;
}
}q[maxn];
void add(int x){
ans+=cnt[a[x]];
for(int i=0;i<26;++i)ans+=cnt[a[x]^(1<<i)];
cnt[a[x]]++;//自己和自己的贡献
}
void del(int x){
cnt[a[x]]--;
for(int i=0;i<26;++i)ans-=cnt[a[x]^(1<<i)];
ans-=cnt[a[x]];
}
int main(){
scanf("%d%d",&n,&m);
scanf("%s",s+1);
for(int i=1;i<=n;++i){
a[i]=a[i-1]^(1<<(s[i]-'a'));
}
for(int i=1;i<=m;++i){
scanf("%d%d",&q[i].L,&q[i].R),q[i].id=i;
}
big=n/sqrt(m);
for(int i=1;i<=n;++i)pos[i]=(i-1)/big+1;
sort(q+1,q+1+m);
pl=1,pr=0;
cnt[0]=1;
for(int i=1;i<=m;++i){
int l=q[i].L,r=q[i].R;
while(pl>l)add(--pl-1);
while(pr<r)add(++pr);
while(pl<l)del(pl++-1);
while(pr>r)del(pr--);
sum[q[i].id]=ans;
}
for(int i=1;i<=m;++i)cout<<sum[i]<<"\n";
return 0;
}