后缀数组 Distinct Substrings SPOJ - DISUBSTR /New Distinct Substrings SPOJ - SUBST1

后缀数组-处理字符串的有力工具 : 点击查看

后缀数组模板及代码详解:点击查看

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.

题意:求一个字符出串里面不同子串的个数

题解:hight 表示公共前缀的长度,总数 - height[i](i>=n) 即可 两个题是一样的,注意第二个用longlong

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
const int N=1100;
int t1[N],t2[N],sum[N],rk[N],ht[N],sa[N],str[N],n;
char s[N];
void get_sa(int n,int m)
{
	int *x=t1,*y=t2;
	for(int i=0;i<m;i++) sum[i]=0;
	for(int i=0;i<n;i++) sum[x[i]=str[i]]++;
	for(int i=1;i<m;i++) sum[i]+=sum[i-1];
	for(int i=n-1;i>=0;i--) sa[--sum[x[i]]]=i;
	for(int p,j=1;p<=n;j<<=1)
	{
		p=0;
		for(int i=n-j;i<n;i++) y[p++]=i;
		for(int i=0;i<n;i++) if(sa[i]>=j) y[p++]=sa[i]-j;
		for(int i=0;i<m;i++) sum[i]=0;
		for(int i=0;i<n;i++) sum[x[y[i]]]++;
		for(int i=1;i<m;i++) sum[i]+=sum[i-1];
		for(int i=n-1;i>=0;i--) sa[--sum[x[y[i]]]]=y[i];
		swap(x,y);
		p=1;
		x[sa[0]]=0;
		for(int i=1;i<n;i++) x[sa[i]]=y[sa[i-1]]==y[sa[i]]&&y[sa[i-1]+j]==y[sa[i]+j]?p-1:p++;
		if(p>=n) break;
		m=p;
	}
	int k=0;n--;
	for(int i=0;i<=n;i++) rk[sa[i]]=i;
	for(int i=0;i<n;i++)
	{
		if(k)k--;else k=0;
		int j=sa[rk[i]-1];
		while(str[i+k]==str[j+k])k++;
		ht[rk[i]]=k; 
	}
}
int main()
{
	int T;
	char s[1100];
	scanf("%d",&T);
	while(T--)
	{
		scanf("%s",s);
		n=strlen(s);
		for(int i=0;i<n;i++) str[i]=s[i];
		str[n]=0;
		get_sa(n+1,256);
		int ans=(n+1)*n/2;
		for(int i=2;i<=n;i++) ans-=ht[i];
		printf("%d\n",ans);
	}	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/mmk27_word/article/details/87263309