给你一个字符
x
和一个串s,让你找
s
有多少不同的子串包含字符x设
s1,s2
,当其长度不同或者某位字符不同则不同。
此类题一般都是要枚举一维,然后往后找,每次加前面未出现过的新串。为了方便去重,这道题可以先用后缀数组处理出来
sa,height
数组。然后从字典序小的开始往大的找。把
x
出现的位置丢进可变长数组v,可以构成合法串的开始位置就是
x
的位置id为了与之前的不重复,利用
height
的性质可以很快知道
sa[i−1]与sa[i]
的最长公共前缀,
id
与起位置去最大值就是不重复的合法位置了。
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <sstream>
#include <set>
#include <vector>
#include <stack>
#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x,begin())
#define ll long long
#define CLR(x) memset(x, 0, sizeof x)
using namespace std;
const int inf = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int maxn = 1e6 + 10;
const int maxv = 1e3 + 10;
const double eps = 1e-9;
int sa[maxn], rak[maxn], height[maxn];
int wa[maxn], wb[maxn], wv[maxn], c[maxn];
bool cmp(int *r, int a, int b, int l) {
return r[a] == r[b] && r[a + l] == r[b + l];
}
void calcSa(int *r, int *sa, int n, int m) {
int i, j, p, *x = wa, *y = wb;
for(i = 0; i < m; i++) c[i] = 0;
for(i = 0; i < n; i++) c[x[i] = r[i]]++;
for(i = 1; i < m; i++) c[i] += c[i-1];
for(i = n - 1; ~i; i--) sa[--c[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++) c[i] = 0;
for(i = 0; i < n; i++) c[wv[i]]++;
for(i = 1; i < m; i++) c[i] += c[i-1];
for(i = n - 1; i >= 0; i--) sa[--c[wv[i]]] = y[i];
swap(x, y);
p = 1, x[sa[0]] = 0;
for(i = 1; i < n; i++)
x[sa[i]] = cmp(y, sa[i-1], sa[i], j) ? p - 1 : p++;
if(p >= n) break;
}
}
void calcHeight(int *r, int *sa, int n) {
int i, j, p = 0;
for(i = 1; i <= n; i++)
rak[sa[i]] = i;
for(i = 0; i < n; i++) {
j = sa[rak[i] - 1];
while(r[i+p] == r[j+p]) p++;
height[rak[i]] = p;
if(p > 0) p--;
}
}
char s[maxn];
int r[maxn];
int main() {
#ifdef LOCAL
freopen("C:\\Users\\Administrator\\Desktop\\in.txt", "r", stdin);
freopen("C:\\Users\\Administrator\\Desktop\\out.txt","w",stdout);
#endif
int T;
int cas = 0;
scanf("%d", &T);
while(T--) {
char t[10];
scanf("%s%s", t, s);
int len = strlen(s);
std::vector<int> v;
for(int i = 0; i < len; i++) {
if(s[i] == t[0])
v.push_back(i);
r[i] = s[i] - 'a' + 1;
}
r[len] = 0;
calcSa(r, sa, len + 1, 30);
calcHeight(r, sa, len);
ll ans = 0;
for(int i = 1; i <= len; i++) {
auto iter = lower_bound(ALL(v), sa[i]);
if(iter == v.end()) continue;
int id = *iter;
id = max(id, sa[i] + height[i]);
ans += len - id;
}
printf("Case #%d: %lld\n", ++cas, ans);
}
return 0;
}