记得KPM出的题中有过类似的。。
先求出前缀,然后符合题意的条件的i和j满足a[i]-a[j]==b[i]-b[j]==c[i]-c[j]
等价转换得a[i]-b[i]==a[j]-b[j]&&a[i]-c[i]==a[j]-c[j]
所以a[i]-b[i]和a[i]-c[i]用hash记录就可以了(我懒直接用map了
1 #include<bits/stdc++.h> 2 #define inc(i,l,r) for(int i=l;i<=r;i++) 3 #define dec(i,l,r) for(int i=l;i>=r;i--) 4 #define link(x) for(edge *j=h[x];j;j=j->next) 5 #define mem(a) memset(a,0,sizeof(a)) 6 #define inf 1e9 7 #define ll long long 8 #define succ(x) (1<<x) 9 #define lowbit(x) (x&(-x)) 10 #define NM 200000+5 11 using namespace std; 12 int read(){ 13 int x=0,f=1;char ch=getchar(); 14 while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} 15 while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); 16 return x*f; 17 } 18 char st[NM]; 19 int n,a[NM],b[NM],c[NM],ans,tot; 20 map<pair<int,int>,int>h; 21 int main(){ 22 freopen("data.in","r",stdin); 23 n=read(); 24 scanf("%s",st); 25 inc(i,1,n){ 26 a[i]=a[i-1];b[i]=b[i-1];c[i]=c[i-1]; 27 switch(st[i-1]){ 28 case 'J':a[i]++;break; 29 case 'I':b[i]++;break; 30 case 'O':c[i]++;break; 31 } 32 pair<int,int>p=make_pair(a[i]-b[i],a[i]-c[i]); 33 if(h[p])ans=max(ans,i-h[p]);else h[p]=i; 34 if(a[i]==b[i]&&b[i]==c[i])ans=max(ans,i); 35 } 36 printf("%d ",ans); 37 return 0; 38 }