SPOJ 694 Distinct Substrings

Description

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.


后缀数组

#include<iostream>
#include<cmath>
#include<map>
#include<vector>
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int Min = 0;
const int Max = 0x7FFFFFFF;
const int maxn = 20005;
const int bit = 1000005;
class suffix
{
private:
	char s[maxn];
	int r[maxn], w[bit], ss[maxn], h[maxn];
	int sa[maxn], rk[maxn + maxn], size;
	int limit;
public:
	bool get(){
		if (scanf("%s", s + 1) != 1) return false;
		size = strlen(s + 1);
		return true;
	}
	void pre()
	{
		memset(rk, 0, sizeof(rk));
		for (int i = 1; i <= bit; i++) w[i] = 0;
		for (int i = 1; i <= size; i++) w[(int)s[i]]++;
		for (int i = 1; i <= bit; i++) w[i] += w[i - 1];
		for (int i = size; i; i--) sa[w[(int)s[i]]--] = i;
		for (int i = 1, j = 1; i <= size; i++)
			rk[sa[i]] = (s[sa[i]] == s[sa[i + 1]] ? j : j++);
		for (int j = 1; j < size; j += j)
		{
			for (int i = 1; i <= size; i++) w[i] = 0;
			for (int i = 1; i <= size; i++) w[rk[i + j]]++;
			for (int i = 1; i <= size; i++) w[i] += w[i - 1];
			for (int i = size; i; i--) ss[w[rk[i + j]]--] = i;

			for (int i = 1; i <= size; i++) w[i] = 0;
			for (int i = 1; i <= size; i++) w[rk[ss[i]]]++;
			for (int i = 1; i <= size; i++) w[i] += w[i - 1];
			for (int i = size; i; i--) sa[w[rk[ss[i]]]--] = ss[i];

			for (int i = 1, k = 1; i <= size; i++)
				r[sa[i]] = (rk[sa[i]] == rk[sa[i + 1]] && rk[sa[i] + j] == rk[sa[i + 1] + j]) ? k : k++;
			for (int i = 1; i <= size; i++) rk[i] = r[i];
		}
		for (int i = 1, k = 0, j; i <= size; h[rk[i++]] = k)
		for (k ? k-- : 0, j = sa[rk[i] - 1]; s[i + k] == s[j + k]; k++);
	}
	void work()
	{
		int ans = 0;
		for (int i = 1; i <= size; i++)
			ans += size - sa[i] + 1 - h[i];
		printf("%d\n", ans);
	}
}f;

int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		f.get();
		f.pre();
		f.work();
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值