题意:规定每一个字符的”好坏“,求字符串中坏的字符不超过k个的不同的子串有多少个。
数据量是允许n^2的算法过的,一看坏字符的个数是满足区间减法的,就反应过来可以用hash搞了。但是自动机肯定也可以做的。
按照拓扑序遍历每个状态,如果当前状态p的pre状态所表示的最长的子串的坏字符个数大于k的话,那这个状态所表示的子串肯定都不满足条件;否则我们就计算出该状态所表示的所有子串中满足条件有多少个,并将其表示的最长子串的坏字符个数记录下来。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define lng long long
using namespace std;
const int maxn = 5000 + 10;
int str[maxn], len, k;
int good[30];
struct suffix_automaton
{
int ch[maxn][30], pre[maxn], val[maxn];
int c[maxn], top[maxn], p[maxn], sum[maxn];
int sz, last;
void init()
{
pre[0] = -1; last = 0; sz = 1; sum[0] = 0;
memset(ch[0], 0, sizeof(ch[0]));
memset(p, 0xff, sizeof(p));
}
void insert(int x)
{
int p = last, np = sz++;
last = np;
memset(ch[np], 0, sizeof(ch[np]));
val[np] = val[p] + 1;
while(p != -1 && ch[p][x] == 0)
{
ch[p][x] = np;
p = pre[p];
}
if(p == -1) pre[np] = 0;
else
{
int q = ch[p][x];
if(val[q] == val[p] + 1) pre[np] = q;
else
{
int nq = sz++;
memcpy(ch[nq], ch[q], sizeof(ch[q]));
val[nq] = val[p] + 1;
pre[nq] = pre[q];
pre[q] = pre[np] = nq;
while(p != -1 && ch[p][x] == q) { ch[p][x] = nq; p = pre[p]; }
}
}
}
void solve()
{
memset(c, 0, sizeof(c));
for(int i = 0; i < sz; ++i) c[val[i]] += 1;
for(int i = 1; i <= len; ++i) c[i] += c[i - 1];
for(int i = 0; i < sz; ++i) top[--c[val[i]]] = i;
for(int i = 0; ; i = ch[i][str[val[i]]])
{
p[i] = val[i] - 1;
if(val[i] == len) break;
}
for(int i = sz - 1; i > 0; --i)
p[pre[top[i]]] = p[top[i]];
int ans = 0;
for(int i = 1; i < sz; ++i)
{
int u = top[i];
if(sum[pre[u]] <= k)
{
int pos = p[u] - val[pre[u]];
int tmp = sum[pre[u]] + good[str[pos]];
while(tmp <= k)
{
ans++; pos--;
if(pos == p[u] - val[u]) break;
tmp += good[str[pos]];
}
sum[u] = tmp;
}
else sum[u] = k + 1;
}
printf("%d\n", ans);
}
}sam;
char s[maxn];
int main()
{
freopen("in.txt", "r", stdin);
scanf("%s", s); len = strlen(s);
sam.init();
for(int i = 0; i < len; ++i) { str[i] = s[i] - 'a'; sam.insert(str[i]); }
scanf("%s", s);
for(int i = 0; i < 26; ++i) good[i] = !(s[i] - '0');
scanf("%d", &k);
sam.solve();
return 0;
}