spoj Distinct Substrings

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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值