Meaning of the questions : Given a string and character X, ask how many different sub-string contains X
Consider seeking a different suffix array substring method: $ \ sum_ {i = 1 } ^ {n} (len + 1- (sa [i] + height [i])) $
can be seen, the contribution for each i All are substrings to sa [i] starts, respectively sa [i] + height [i ] + 1, sa [i] + height [i] + 2 ··· substring len end, it is only necessary consider the interval [sa [i], sa [ i] + height [i]] , there are no X, if so, the normal statistics, if not, you need to find sa [i] + [i] height behind for the first time position X appears, from the statistics here
it is only necessary after a recording position sa [i] X first appears (used here next [sa [i]] indicates)
the answer is: \ [\ sum_ = {I}. 1 ^ {n} (len + 1 -max (sa [i] + height [i], next [sa [i]])) \]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 100010;
int n;
int sa[maxn], x[maxn], c[maxn], y[maxn], height[maxn];
char s[maxn];
int near[maxn];
void SA()
{
int m = 128;
for (int i = 0; i <= m; i++)
c[i] = 0;
for (int i = 1; i <= n; i++)
c[x[i] = s[i]]++;
for (int i = 1; i <= m; i++)
c[i] += c[i - 1];
for (int i = n; i >= 1; i--)
sa[c[x[i]]--] = i;
for (int k = 1; k <= n; k <<= 1)
{
int p = 0;
for (int i = 0; i <= m; i++)
y[i] = 0;
for (int i = n - k + 1; i <= n; i++)
y[++p] = i;
for (int i = 1; i <= n; i++)
if (sa[i] > k)
y[++p] = sa[i] - k;
for (int i = 0; i <= m; i++)
c[i] = 0;
for (int i = 1; i <= n; i++)
c[x[y[i]]]++;
for (int i = 1; i <= m; i++)
c[i] += c[i - 1];
for (int i = n; i >= 1; i--)
sa[c[x[y[i]]]--] = y[i];
swap(x, y);
x[sa[1]] = 1;
p = 1;
for (int i = 2; i <= n; ++i)
x[sa[i]] = (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k]) ? p : ++p;
if (p >= n)
break;
m = p;
}
}
void get_height()
{
int k = 0;
for (int i = 1; i <= n; ++i)
{
if (x[i] == 1) continue;
if (k) --k;
int j = sa[x[i] - 1];
while (j + k <= n && i + k <= n && s[i + k] == s[j + k]) ++k;
height[x[i]] = k;
}
}
int main()
{
int t;
scanf("%d", &t);
for (int tt = 1; tt <= t; tt++)
{
getchar();
char ch;
scanf("%c%s", &ch, s + 1);
n = strlen(s + 1);
SA();get_height();
memset(near, 0, sizeof(near));
for (int i = n; i >= 1; i--)
{
if (s[i] == ch)
{
int pos = i;
near[i] = i;
i--;
while (i >= 0 && s[i] != ch)
{
near[i] = pos;
i--;
}
i++;
}
}
ll ans = 0;
for (int i = 1; i <= n; i++)
{
if (near[sa[i]] == 0)
continue;
ans += n - max(near[sa[i]], sa[i] + height[i]) + 1;
}
printf("Case #%d: %lld\n", tt, ans);
}
return 0;
}