Spoj SUBST1 New Distinct Substrings

本文介绍了一种通过构建后缀自动机来计算给定字符串所有不同子串数量的方法。适用于处理大量数据输入的情况,例如每组测试用例的字符串长度可达50000。该算法使用C++实现,包括初始化、插入字符、构建后缀自动机和解决计算子串数量等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

就是让你求一下一个串的本质不同的子串的个数。
这个就等价于求一下后缀自动机每个节点的权值和,每个节点的权值等于(max{}-min{}+1)

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
#define maxn 200005
int f[maxn],ch[maxn][26],cnt=1;
int n,siz[maxn],l[maxn],T,las=1;
int a[maxn],c[maxn];
char s[maxn];
ll ans=0;

inline void init(){
	cnt=las=1;
	memset(f,0,sizeof(f));
	memset(ch,0,sizeof(ch));
	memset(c,0,sizeof(c));
	siz[1]=l[1]=ans=0;
}

inline void ins(int x){
	int p=las,np=++cnt;
	las=np,l[np]=l[p]+1;
	siz[np]=1;
	
	for(;p&&!ch[p][x];p=f[p]) ch[p][x]=np;
	if(!p) f[np]=1;
	else{
		int q=ch[p][x];
		if(l[q]==l[p]+1) f[np]=q;
		else{
			int nq=++cnt;
			l[nq]=l[p]+1;
			memcpy(ch[nq],ch[q],sizeof(ch[q]));
			f[nq]=f[q];
			f[q]=f[np]=nq;
			for(;ch[p][x]==q;p=f[p]) ch[p][x]=nq;
		}
	}
}

inline void build(){
	for(int i=0;i<n;i++) ins(s[i]-'a');
}

inline void solve(){
	for(int i=1;i<=cnt;i++) ans+=(ll)(l[i]-l[f[i]]);
}

int main(){
	scanf("%d",&T);
	while(T--){
		init();
		scanf("%s",s);
		n=strlen(s);
		build();
		solve();
		printf("%lld\n",ans);
	}
	
	return 0;
}

  

 

转载于:https://www.cnblogs.com/JYYHH/p/8456400.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值