Distinct Substrings 【SPOJ - DISUBSTR】【后缀数组求不同子串个数】
程序员文章站
2022-04-17 14:04:06
...
题目链接
求不同子串的个数。
于是,我们可以考虑成,一个后缀,和它前一个sa的后缀有多少个不重叠的前缀子串。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
//#include <unordered_map>
//#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 1e3 + 7, maxM = 3e3 + 10;
struct SA
{
int n, m;
int s[maxN];
int y[maxN], x[maxN], c[maxM], sa[maxN], rk[maxN], height[maxN];
inline void get_SA()
{
for(int i=1; i<=m; i++) c[i] = 0; //桶的初始化
for(int i=1; i<=n; i++) ++c[x[i] = s[i]];
for(int i=2; i<=m; i++) c[i] += c[i - 1]; //利用差分前缀和的思想知道每个关键字最多是在第几名
for(int i=n; i>=1; i--) sa[c[x[i]]--] = i;
for(int k=1; k<=n; k<<=1)
{
int num = 0;
for(int i=n - k + 1; i<=n; i++) y[++num] = i;
for(int i=1; i<=n; i++) if(sa[i] > k) y[++num] = sa[i] - k; //是否可以作为第二关键字
for(int i=1; i<=m; i++) c[i] = 0;
for(int i=1; i<=n; i++) c[x[i]]++; //因为上一次循环已经求出这次的第一关键字了
for(int i=2; i<=m; i++) c[i] += c[i - 1];
for(int i=n; i>=1; i--) //在同一第一关键字下,按第二关键字来排
{
sa[c[x[y[i]]]--] = y[i];
y[i] = 0;
}
swap(x, y);
x[sa[1]] = 1; num = 1;
for(int i=2; i<=n; i++)
{
x[sa[i]] = (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k]) ? num : ++num;
}
if(num == n) break;
m = num;
}
}
inline void get_height()
{
int k = 0;
for(int i=1; i<=n; i++) rk[sa[i]] = i;
for(int i=1; i<=n; i++)
{
if(rk[i] == 1) continue; //第一名的height为0
if(k) k--; //height[i] >= height[i - 1] - 1
int j = sa[rk[i] - 1];
while(j + k <= n && i + k <= n && s[i + k] == s[j + k]) k++;
height[rk[i]] = k;
}
}
inline void clear()
{
n = 0; m = 307;
}
} sa;
int N;
char s[maxN];
signed main()
{
int T; scanf("%d", &T);
while(T--)
{
sa.clear();
scanf("%s", s + 1);
N = (int)strlen(s + 1);
for(int i=1; i<=N; i++) sa.s[++sa.n] = s[i];
sa.s[++sa.n] = 300;
sa.get_SA();
sa.get_height();
ll ans = 0;
for(int i=1; i<=N; i++)
{
ans += (N - sa.sa[i] + 1) - sa.height[i];
}
printf("%lld\n", ans);
}
return 0;
}