spoj Distinct Substrings

来源:互联网 发布:中巴公路 知乎 编辑:程序博客网 时间:2024/06/05 19:28

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-1个height。

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int maxm = 10005;int Height[maxm], a[maxm], s[maxm], sa[maxm], tp[maxm], Rank[maxm];int n, m;char str[maxm];int cmp(int *f, int x, int y, int w){return f[x] == f[y] && f[x + w] == f[y + w];}void Rsort(){for (int i = 0;i <= m;i++) s[i] = 0;for (int i = 1;i <= n;i++) s[Rank[tp[i]]]++;for (int i = 1;i <= m;i++) s[i] += s[i - 1];for (int i = n;i >= 1;i--) sa[s[Rank[tp[i]]]--] = tp[i];}void suffix(){for (int i = 1;i <= n;i++) Rank[i] = a[i], tp[i] = i;m = 30, Rsort();for (int i, w = 1, p = 1;p < n;w += w, m = p){for (p = 0, i = n - w + 1;i <= n;i++) tp[++p] = i;for (i = 1;i <= n;i++) if (sa[i] > w) tp[++p] = sa[i] - w;Rsort(), swap(Rank, tp), Rank[sa[1]] = p = 1;for (i = 2;i <= n;i++) Rank[sa[i]] = cmp(tp, sa[i], sa[i - 1], w) ? p : ++p;}int j, k = 0;for (int i = 1;i <= n;Height[Rank[i++]] = k)for (k = k ? k - 1 : k, j = sa[Rank[i] - 1];a[i + k] == a[j + k];k++);}int main(){int i, j, k, sum, t;scanf("%d", &t);while (t--){scanf("%s", str);n = strlen(str);for (i = 0;str[i] != '\0';i++) a[i + 1] = str[i] - 'A' + 1;suffix();sum = n*(n + 1) / 2;for (i = 2;i <= n;i++) sum -= Height[i];printf("%d\n", sum);}return 0;}


原创粉丝点击