后缀数组的一个功效是统计一个串里多少个不同的子串。
这个题就稍微改了一下,其实大体做法不变。
他要求 至少包含1个指定字母 的子串。
所以反过来想,所有子串 减去 不包含指定的子串 就可以了。
前者是个基本问题,重点是后者。
字符串从后向前扫描一遍,处理出每个字符开始,向前延伸最大多少,不包含指定字母(near数组)。
然后就相当于每个后缀都减少了一段,并且要改造height数组。
height[i]=min(height[i],min( near[sa[i-1]], near[sa[i]]))
然后再对这个新的后缀组做一遍相同的事情就可以了。
答案减一减即可,注意要用long long int
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#define LL long long int
using namespace std;
const int nMax = 400001;
char arr[nMax+1];
int sa[nMax], rk[nMax], height[nMax];
int wa[nMax], wb[nMax], wv[nMax], wd[nMax];
int n,k;
char str[nMax];
char C;
int cmp(int *r, int a, int b, int l){
return r[a] == r[b] && r[a+l] == r[b+l];
}
void da(char *r, int n, int m){ // 倍增算法 r为待匹配数组 n为总长度 m为字符范围
int i, j, p, *x = wa, *y = wb, *t;
for(i = 0; i < m; i ++) wd[i] = 0;
for(i = 0; i < n; i ++) wd[x[i]=r[i]] ++;
for(i = 1; i < m; i ++) wd[i] += wd[i-1];
for(i = n-1; i >= 0; i --) sa[-- wd[x[i]]] = i;
for(j = 1, p = 1; p < n; j *= 2, m = p){
for(p = 0, i = n-j; i < n; i ++) y[p ++] = i;
for(i = 0; i < n; i ++) if(sa[i] >= j) y[p ++] = sa[i] - j;
for(i = 0; i < n; i ++) wv[i] = x[y[i]];
for(i = 0; i < m; i ++) wd[i] = 0;
for(i = 0; i < n; i ++) wd[wv[i]] ++;
for(i = 1; i < m; i ++) wd[i] += wd[i-1];
for(i = n-1; i >= 0; i --) sa[-- wd[wv[i]]] = y[i];
for(t = x, x = y, y = t, p = 1, x[sa[0]] = 0, i = 1; i < n; i ++){
x[sa[i]] = cmp(y, sa[i-1], sa[i], j) ? p - 1: p ++;
}
}
}
void calHeight(char *r, int n){ // 求height数组。
int i, j, k = 0;
for(i = 1; i <= n; i ++) rk[sa[i]] = i;
for(i = 0; i < n; height[rk[i ++]] = k){
for(k ? k -- : 0, j = sa[rk[i]-1]; r[i+k] == r[j+k]; k ++);
}
}
int near[nMax];//以他开始的多少个字母不包含C
void init()
{
memset(near,0,sizeof(near));
}
int main()
{
int TT;cin>>TT;
for(int CS=1;CS<=TT;CS++)
{
init();
cin>>C;
scanf("%s",str);
int len=strlen(str);
str[len]=0;
da(str,len+1,140);
calHeight(str,len);
LL ans=0;
for(int i=1;i<=len;i++)
{
ans+=len-sa[i]-height[i];
}
for(int i=0;i<len;i++)
{
near[i]=len;
}
int idx=len-1;
int cnt=0;
while(idx>=0)
{
if(str[idx]==C)
{
near[idx]=0;
cnt=0;
idx--;
continue;
}
else
{
cnt++;
near[idx]=cnt;
idx--;
continue;
}
}
for(int i=1;i<=len;i++)
{
height[i]=min(height[i],min(near[sa[i-1]],near[sa[i]]));
}
LL tmp=0;
for(int i=1;i<=len;i++)
{
tmp+=near[sa[i]]-height[i];
}
printf("Case #%d: %lld\n",CS,ans-tmp);
}
return 0;
}