SPOJ 705 New 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 <= 50000

Output

For each test case output one number saying the number of distinct substrings.

Example

Input:
2
CCCCC
ABABA

Output:
5

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 = 50005;
const int bit = 256;
class suffix
{
private:
	char s[maxn];
	int r[maxn], w[maxn], 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()
	{
		long long ans = 0;
		for (int i = 1; i <= size; i++)
			ans += size - sa[i] + 1 - h[i];
		printf("%lld\n", ans);
	}
}f;

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


你可能感兴趣的:(spoj)