链接
题解
枚举六种排列,然后把串变化一下,6个串都扔进广义后缀自动机,然后求串的种类数
对于只包含一种字符的串,每种串都恰好被算了三次,分别作为aaaa…a,bbb…b,ccc.c被各算了一次
包含两种字符、或者包含三种字符的串,每种串都被恰好算了六次
而只包含一种字符的串的种类数,可以通过求最长连续相同字符个数求出来,这样我就可以把这种串的次数也凑到6次,加进答案里,最后除以6就行了
代码
#include <bits/stdc++.h>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 300010
#define cl(x) memset(x,0,sizeof(x))
#define rep(i,a,b) for(i=a;i<=b;i++)
#define drep(i,a,b) for(i=a;i>=b;i--)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
ll c, f(1);
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
for(;isdigit(c);c=getchar())x=x*10+c-0x30;
return f*x;
}
struct Trie
{
int tot, ch[maxn][3], end[maxn];
void init(){while(tot--)cl(ch[tot+1]),end[tot+1]=0;tot=1;}
int* operator[](int index){return ch[index];}
int id(char c){return c-'a';}
int append(int pos, int c)
{
int &t=ch[pos][c];
return t?t:t=++tot;
}
int insert(char* s, int n)
{
int pos=1, i;
for(i=1;i<=n;i++)pos=append(pos,id(s[i]));
end[pos]++;
return pos;
}
}trie;
struct EXSAM
{
int tot, ch[maxn<<1][3], fa[maxn<<1], len[maxn<<1], pref[maxn<<1];
int* operator[](int u){return ch[u];}
void init()
{
int i;
rep(i,1,tot)cl(ch[i]),fa[i]=len[i]=pref[i]=0;
tot=1;
}
int append(int las, int c)
{
int p(las);
len[las=++tot]=len[p]+1;
pref[las]=1;
for(;p and !ch[p][c];p=fa[p])ch[p][c]=las;
if(!p)fa[las]=1;
else
{
int q=ch[p][c];
if(len[q]==len[p]+1)fa[las]=q;
else
{
int qq=++tot;
memcpy(ch[qq],ch[q],sizeof(ch[q]));
fa[qq]=fa[q];
len[qq]=len[p]+1;
fa[q]=fa[las]=qq;
for(;ch[p][c]==q;p=fa[p])ch[p][c]=qq;
}
}
return las;
}
void bfs_build(Trie& trie)
{
queue<pii> q;
q.em(pii(1,1));
while(!q.empty())
{
auto pr=q.front(); q.pop();
int pos=pr.first, u=pr.second;
for(int i=0;i<3;i++)
if(trie[pos][i])
{
int to=trie[pos][i], v=ch[u][i]?ch[u][i]:append(u,i);
q.em(pii(to,v));
}
}
}
int mov(int p, int c){return max(1,ch[p][c]);}
}exsam;
char s[maxn], t[maxn];
int main()
{
ll n;
while(~scanf("%lld",&n))
{
scanf("%s",s+1);
ll f[300], i, mx=0, now=0, ans=0;
rep(i,1,n)
{
if(s[i]==s[i-1])now++;
else now=1;
mx=max(now,mx);
}
f['a'] = 'a', f['b'] = 'b', f['c'] = 'c';
exsam.init();
trie.init();
do
{
rep(i,1,n)t[i]=f[s[i]];
trie.insert(t,n);
}
while(next_permutation(f+'a',f+'a'+3));
exsam.bfs_build(trie);
rep(i,1,exsam.tot)ans += exsam.len[i]-exsam.len[exsam.fa[i]];
ans += 3*mx;
printf("%lld\n",ans/6);
}
return 0;
}