摘要:SA板题

luogu2408不同子串个数

题面

题目分析

就一个板题没啥好说的…

因为用height可以求出后缀排序后相邻两串的lcp,即为重复的子串,减掉就好了.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "iostream"
#include "cstdlib"
#include "cstdio"
#include "cstring"
#include "cmath"
#include "cctype"
#include "ctime"
#include "iomanip"
#include "algorithm"
#include "set"
#include "queue"
#include "map"
#include "stack"
#include "deque"
#include "vector"
#define R register
#define INF 0x3f3f3f3f
#define debug(x) printf("debug:%lld\n",x)
#define debugi(x) printf("debug:%d\n",x)
#define debugf(x) printf("debug:%llf\n",x)
#define endl putchar('\n')
typedef long long lxl;
const lxl big=100010;
lxl n,m=100,ans;
lxl rank[big],sa[big],tp[big],suf[big],pla[big],height[big];
char s[big];
inline lxl read()
{
char c(getchar());
lxl f(1),x(0);
for(;!isdigit(c);(c=='-')&&(f=-1),c=getchar());
for(;isdigit(c);x=(x<<1)+(x<<3)+(c^48),c=getchar());
return f*x;
}
inline void QSort()
{
for(R int i(0);i<=m;++i)suf[i]=0;
for(R int i(1);i<=n;++i)++suf[rank[i]];
for(R int i(1);i<=m;++i)suf[i]+=suf[i-1];
for(R int i(n);i;--i)sa[suf[rank[tp[i]]]--]=tp[i];
}
inline void SuffixSort()
{
for(R int i(1);i<=n;++i)rank[i]=s[i]-'#',tp[i]=i;
QSort();
for(R int w(1),p(0);p<n;m=p,w<<=1)
{
p=0;
for(R int i(1);i<=w;++i)tp[++p]=n-w+i;
for(R int i(1);i<=n;++i)if(sa[i]>w)tp[++p]=sa[i]-w;
QSort();
std::swap(tp,rank);
rank[sa[1]]=p=1;
for(R int i(2);i<=n;++i)
rank[sa[i]]=(tp[sa[i]]==tp[sa[i-1]]&&tp[sa[i]+w]==tp[sa[i-1]+w])?p:++p;
}
}
int main(void)
{
n=read();scanf("%s",s+1);
for(R int i(1);i<=n;++i)pla[i]=i;
SuffixSort();
for(R int i(1),j(0);i<=n;++i)
{
if(j)--j;
while(s[i+j]==s[sa[rank[i]-1]+j])++j;
height[rank[i]]=j;
}
for(R int i(1);i<=n;++i)ans+=n-pla[sa[i]]+1-height[i];
printf("%lld\n",ans);
return 0;
}