SPOJ694 Distinct Substrings (trie 树)

来源:互联网 发布:淘宝卖家怎么注册帐号 编辑:程序博客网 时间:2024/05/29 18:10

题意:

        给出一个字符串,问有几个不同子串

思路:

        问不同子串的个数,如果用 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.



0 0
原创粉丝点击