SPOJ Distinct Substrings【后缀数组】

时间:2021-05-14 04:45:24

Given a string, we need to find the total number of its distinct substrings.

Input

T- number of test cases. T<=20;
Each test case consists of one string, whose length is <= 1000

Output

For each test case output one number saying the number of distinct substrings.

Example

Sample Input:
2
CCCCC
ABABA

Sample Output:
5
9

Explanation for the testcase with string ABABA: 
len=1 : A,B
len=2 : AB,BA
len=3 : ABA,BAB
len=4 : ABAB,BABA
len=5 : ABABA
Thus, total number of distinct substrings is 9.

题意:

求一个字符串中所有的不相同的子串个数。

思路:

一个字符串的所有子串个数是n*(n+1)/2,关键就是有多少是重复的。

一个子串其实就是原字符串某个后缀的前缀,找到有多少重复的其实就是找后缀的lcp

比如我们遍历到了第k个后缀,本来他可以产生len个前缀,但是他的前面有一部分前缀是已经算过的了。

而且由于 LCP(i,j)=min{LCP(k-1,k)|i+1≤k≤j} ,且对 i≤j<k,LCP(j,k)≥LCP(i,k)

每加入一个后缀,应该减去max(LCP(i,j)), 也就是LCP(i-1,i),也就是height[i]

 #include <iostream>
#include <set>
#include <cmath>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
using namespace std;
typedef long long LL;
#define inf 0x7f7f7f7f const int maxn = ;
int t;
char str[maxn]; int sa[maxn];
int t1[maxn], t2[maxn], c[maxn];
int rnk[maxn], height[maxn]; void build_sa(int s[], int n, int m)
{
int i, j, p, *x = t1, *y = t2;
for(i = ; i < m; i++)c[i] = ;
for(i = ; i < n; i++)c[x[i] = s[i]]++;
for(i = ; i < m; i++)c[i] += c[i - ];
for(i = n - ; i >= ; i--)sa[--c[x[i]]] = i;
for(j = ; j <= n; j <<= ){
p = ;
for(i = n - j; i < n; i++)y[p++] = i;
for(i = ; i < n; i++)if(sa[i] >= j)y[p++] = sa[i] - j;
for(i = ; i < m; i++)c[i] = ;
for(i = ; i < n; i++)c[x[y[i]]]++;
for(i = ; i < m; i++)c[i] += c[i - ];
for(i = n - ; i >= ; i--)sa[--c[x[y[i]]]] = y[i];
swap(x, y);
p = ;
x[sa[]] = ;
for(i = ; i < n; i++)
x[sa[i]] = y[sa[i - ]] == y[sa[i]] && y[sa[i - ] + j] == y[sa[i] + j] ? p - :p++;
if(p >= n)break;
m = p;
}
} void get_height(int s[], int n)
{
int i, j, k = ;
for(i = ; i <= n; i++)rnk[sa[i]] = i;
for(i = ; i < n; i++){
if(k) k--;
j = sa[rnk[i] - ];
while(s[i + k] == s[j + k])k++;
height[rnk[i]] = k;
}
} int s[maxn];
int main()
{
scanf("%d", &t);
while(t--){
scanf("%s", str);
int n = strlen(str);
for(int i = ; i <= n; i++)s[i] = str[i];
build_sa(s, n + , );
get_height(s, n);
LL ans = n * (n + ) / ;
//cout<<ans<<endl;
for(int i = ; i <= n; i++){
ans -= height[i];
}
printf("%lld\n", ans); }
return ;
}