SPOJ 694 (后缀数组) Distinct Substrings

将所有后缀按照字典序排序后,每新加进来一个后缀,它将产生n - sa[i]个前缀。这里和小罗论文里边有点不太一样。

height[i]为和字典序前一个的LCP,所以还要减去,最终累计n - sa[i] - height[i]即可。

 1 #include <cstdio>

 2 #include <cstring>

 3 #include <algorithm>

 4 using namespace std;

 5 

 6 const int maxn = 100000 + 10;

 7 char s[maxn];

 8 int sa[maxn], rank[maxn], height[maxn];

 9 int t[maxn], t2[maxn], c[maxn];

10 int n;

11 

12 void build_sa(int n, int m)

13 {

14     int i, *x = t, *y = t2;

15     for(i = 0; i < m; i++) c[i] = 0;

16     for(i = 0; i < n; i++) c[x[i] = s[i]]++;

17     for(i = 1; i < m; i++) c[i] += c[i - 1];

18     for(i = n - 1; i >= 0; i--) sa[--c[x[i]]] = i;

19     for(int k = 1; k <= n; k <<= 1)

20     {

21         int p = 0;

22         for(i = n - k; i < n; i++) y[p++] = i;

23         for(i = 0; i < n; i++) if(sa[i] >= k) y[p++] = sa[i] - k;

24         for(i = 0; i < m; i++) c[i] = 0;

25         for(i = 0; i < n; i++) c[x[y[i]]]++;

26         for(i = 1; i < m; i++) c[i] += c[i - 1];

27         for(i = n - 1; i >= 0; i--) sa[--c[x[y[i]]]] = y[i];

28         swap(x, y);

29         p = 1; x[sa[0]] = 0;

30         for(i = 1; i < n; i++)

31             x[sa[i]] = y[sa[i]]==y[sa[i-1]] && y[sa[i]+k]==y[sa[i-1]+k] ? p - 1 : p++;

32         if(p >= n) break;

33         m = p;

34     }

35 }

36 

37 void build_height()

38 {

39     int k = 0;

40     for(int i = 1; i <= n; i++) rank[sa[i]] = i;

41     for(int i = 0; i < n; i++)

42     {

43         if(k) k--;

44         int j = sa[rank[i] - 1];

45         while(s[i + k] == s[j + k]) k++;

46         height[rank[i]] = k;

47     }

48 }

49 

50 int main()

51 {

52     //freopen("in.txt", "r", stdin);

53 

54     int T; scanf("%d", &T);

55     while(T--)

56     {

57         scanf("%s", s);

58         n = strlen(s);

59         memset(sa, 0, sizeof(sa));

60         build_sa(n + 1, 256);

61         build_height();

62 

63         int ans = 0;

64         for(int i = 1; i <= n; i++)

65             ans += n - sa[i] - height[i];

66         printf("%d\n", ans);

67     }

68 

69     return 0;

70 }
代码君

 

你可能感兴趣的:(substring)