SP705 SUBST1 - New Distinct Substrings
\(\color{#0066ff}{ 题目描述 }\)
给定一个字符串,求该字符串含有的本质不同的子串数量。
\(\color{#0066ff}{输入格式}\)
T- number of test cases. T<=20; Each test case consists of one string, whose length is <= 50000
\(\color{#0066ff}{输出格式}\)
For each test case output one number saying the number of distinct substrings.
\(\color{#0066ff}{输入样例}\)
2
CCCCC
ABABA
\(\color{#0066ff}{输出样例}\)
5
9
\(\color{#0066ff}{数据范围与提示}\)
none
\(\color{#0066ff}{ 题解 }\)
本质不同字串???
这不就是自动机上所有节点维护的所有串吗
作为一个最简自动机,这才是真正的板子题吧qwq
\(ans = \sum{len[o] - len[fa[o]]}\)
#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL in() {
char ch; int x = 0, f = 1;
while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
return x * f;
}
const int maxn = 1e5 + 5;
struct SAM {
protected:
struct node {
node *ch[26], *fa;
int len, siz;
node(int len = 0, int siz = 0): fa(NULL), len(len), siz(siz) {
memset(ch, 0, sizeof ch);
}
};
node *root, *tail, *lst;
node pool[maxn];
node *extend(int c) {
node *o = new(tail++) node(lst->len + 1, 1), *v = lst;
for(; v && !v->ch[c]; v = v->fa) v->ch[c] = o;
if(!v) o->fa = root;
else if(v->len + 1 == v->ch[c]->len) o->fa = v->ch[c];
else {
node *n = new(tail++) node(v->len + 1), *d = v->ch[c];
std::copy(d->ch, d->ch + 26, n->ch);
n->fa = d->fa, d->fa = o->fa = n;
for(; v && v->ch[c] == d; v = v->fa) v->ch[c] = n;
}
return lst = o;
}
public:
void clr() {
tail = pool;
root = lst = new(tail++) node();
}
SAM() { clr(); }
LL ins(char *s) {
LL ans = 0;
for(char *p = s; *p; p++) {
node *o = extend(*p - 'a');
ans += o->len - o->fa->len;
}
return ans;
}
}sam;
char s[maxn];
int main() {
for(int T = in(); T --> 0;) {
scanf("%s", s);
printf("%lld\n", sam.ins(s));
sam.clr();
}
return 0;
}
----olinr