hdu 5769 Substring
题意很简单,给你一个串和一个字符,问你含有这个字符的这个串的子串有几个
后缀自动机应该能使,但是不会,多校结束之后用后缀数组过掉的
一个串的连续子串的总数: sigma(len - height[I] - suffixarray[I])
那么带有该字符的只要填一点东西进去就可以求了
也就是在 (height[I] + suffixarray[I])和 该后缀后方第一个该字符的位置 这两个值里面选一个最大值就行了
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int SIZE = 100005;
struct suffixArray
{
int wa[SIZE], wb[SIZE], wv[SIZE], ws[SIZE];
int sa[SIZE];//后缀数组
int height[SIZE];
int rank[SIZE];
int r[SIZE];//转化后的数组,长度比源字符串长1
int len;
int Max;//用于基数排序,是字符串中的最大值
//int n, m;
void init()
{
memset(r, 0, sizeof r);
}
void clear()
{
Max = len = 0;
memset(sa, 0, sizeof sa);
memset(height, 0, sizeof height);
memset(rank, 0, sizeof rank);
memset(r, 0, sizeof r);
}
int cmp(int *r, int a, int b, int l)
{
return r[a] == r[b] && r[a + l] == r[b + l];
}
//尾部自动添 0,并增加字符串长度(+1),为了基数排序不出错
int go(char *str)
{
int tmp = 0;
Max = 0;
for (int i = 0; str[i]; i++)
{
r[i] = str[i] - 'a' + 1;
Max = max(Max, r[i]);
tmp++;
}
r[tmp++] = 0;
len = tmp;
return tmp;
}
void doubleAdd()
{
//go(str);
//Max = 27;
int i, j, p;
int n = len, m = Max + 1;
int *x = wa, *y = wb, *t;
// 对长度为1的串进行排序
for (i = 0; i < m; i++)
ws[i] = 0;
for (i = 0; i < n; i++)
ws[x[i] = r[i]]++;
for (i = 1; i < m; i++)
ws[i] += ws[i - 1];
for (i = n - 1; i >= 0; i--)
sa[--ws[x[i]]] = i;
//j为当前字符串长度,y是第二关键字排序的结果
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++)
ws[i] = 0;
for (i = 0; i < n; i++)
ws[wv[i]]++;
for (i = 1; i < m; i++)
ws[i] += ws[i - 1];
for (i = n - 1; i >= 0; i--)
sa[--ws[wv[i]]] = y[i];
//到此求出新的sa值
//计算新的rank值,这里之前y已经没用了,就利用y来保存rank
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++;
}
return;
}
void calHeight()
{
int i, j, k = 0;
for (i = 1; i < len; i++)
rank[sa[i]] = i;
for (i = 0; i < len; height[rank[i++]] = k)
{
//寻找当前长度的串排名前一位的串,这次求得height的值一定是上一次求得的height值-1
if (rank[i] > 0)
for (k ? k-- : 0, j = sa[rank[i] - 1]; r[i + k] == r[j + k]; k++);
else k = 0;
}
return;
}
}SA;
int main(void)
{
//freopen("C:\\Users\\wLIEd\\Desktop\\in.txt", "r", stdin);
char ch;
char str[SIZE];
int T;
int cas = 1;
int len;
long long ans;
cin >> T;
while (T--)
{
ans = 0;
cin >> ch;
cin >> str;
SA.clear();
len = SA.go(str);
SA.doubleAdd();
SA.calHeight();
for (int i = 1; i < len; i++)
{
for (int j = SA.sa[i]; j < len; j++)
{
if (str[j] == ch)
{
if (j <= SA.sa[i] + SA.height[i])
{
ans += len - SA.sa[i] - SA.height[i] - 1;
break;
}
else
{
ans += len - j - 1;
break;
}
}
}
}
cout << "Case #" << cas++ << ": " << ans << endl;
}
return 0;
}