题意:
给出一个字符串,问有几个不同子串
思路:
问不同子串的个数,如果用 trie 树来理解的话就是,问 trie 树的节点个数。算法复杂度在O(n^2)
代码:( trie 树的建立使用了 Kuangbin 大大的 AC自动机模板)
由于 AC 自动机大部分时间损耗在初始化 每个节点上,故经过“测试”,本题字符在 ' ! ' 到 ' Z ' 之间,优化至 70 ms。(若直接用 128 的数组,160ms已超时)
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
int ans;char buf[2000];
struct Trie
{
int next[500010][60];
int root,L;
int newnode()
{
for(int i = 0; i < 60; i++)
next[L][i] = -1;
L++;
ans++;
return L-1;
}
void init()
{
L = 0;
root = newnode();
}
void insert(int k,int len)
{
int now = root;
for(int i = k; i < len; i++)
{
if(next[now][buf[i]-'!'] == -1)
next[now][buf[i]-'!'] = newnode();
now = next[now][buf[i]-'!'];
}
}
};
Trie ac;
int main()
{
int T;
scanf("%d",&T);
getchar();
while(T--)
{
gets(buf);
int len=strlen(buf);
ac.init();
ans=0;
for(int i = 0; i < len; i++)
ac.insert(i,len);
printf("%d\n",ans);
}
return 0;
}
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.
该博客介绍了如何使用Trie树解决寻找字符串不同子串数量的问题。题目要求求解给定字符串的不重复子串个数,通过建立Trie树可以将算法复杂度降低到O(n^2)。博主分享了使用Kuangbin大大的AC自动机模板建立Trie树的代码,并针对字符范围进行优化,从而在限制时间内得到解决方案。博客提供了样例输入和输出,解释了不同长度子串的计数方式。
2万+

被折叠的 条评论
为什么被折叠?



