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*(n+1)/2个子串,再减去相同的子串就行了
对于子串,它肯定是一个后缀的前缀,如果height[i]==k,说明后缀i-1和后缀i有k个子串相同,这样减去它即可,即减去height数组的后n-1个即可
参考题解
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e4+5;
char str[maxn];
int _rank[maxn], sa[maxn], height[maxn], _temp[maxn], bucket[maxn];
int n, m; //m是自己定的,其实就是字母字符所占ascii码最大值,即桶的个数
void RadixSort()
{
for(int i = 0; i <= m; i++) bucket[i] = 0; //clear the buckets
for(int i = 1; i <= n; i++) bucket[_rank[_temp[i]]]++; //statistics the number of each position's rank
for(int i = 1; i <= m; i++) bucket[i] += bucket[i-1]; //solve the sum of prefixes
for(int i = n; i >= 1; i--) sa[bucket[_rank[_temp[i]]]--] = _temp[i];
}
void GetSa()
{
for(int i = 1; i <= n; i++) _rank[i] = str[i], _temp[i] = i;
RadixSort();
for(int _size = 1; _size <= n; _size <<= 1)
{
int num = 0;
for(int i = n-_size+1; i <= n; i++) _temp[++num] = i;
for(int i = 1; i <= n; i++) if(sa[i] > _size) _temp[++num] = sa[i]-_size;
RadixSort(); swap(_rank, _temp);
_rank[sa[1]] = num = 1;
for(int i = 2; i <= n; i++)
_rank[sa[i]] = (_temp[sa[i]] == _temp[sa[i-1]] && _temp[sa[i]+_size] == _temp[sa[i-1]+_size]) ? num : ++num;
if(num == n) break ;
m = n;
}
}
void GetHeight()
{
for(int i = 1; i <= n; i++) _rank[sa[i]] = i;
int prefix_len = 0;
for(int i = 1; i <= n; i++)
{
if(_rank[i] == 1) continue ;
if(prefix_len) --prefix_len;
int pre_pos = sa[_rank[i]-1];
while(i+prefix_len <= n && pre_pos+prefix_len <= n && str[i+prefix_len] == str[pre_pos+prefix_len]) ++prefix_len;
height[_rank[i]] = prefix_len;
}
}
int main()
{
int T;
cin >> T;
while(T--)
{
scanf("%s", str+1);
n = strlen(str+1);
m = 'z';
GetSa();
GetHeight();
int sum = ((n+1)*n)>>1;
for(int i = 1; i <= n; i++) sum -= height[i];
printf("%d\n", sum);
}
return 0;
}