【SPOJ DISUBSTR】Distinct Substrings 后缀数组

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.


SPOJ还有一个题是【SUBST1 - New Distinct Substrings】,一模一样,不过nlog^2n过不了。

计数问题,贡献是当前后缀生成的子串数目减去高度数组的大小,也就是重复的子串数目。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

typedef long long LL;

const int SZ = 1000010;

int lcp[SZ],sa[SZ],tmp[SZ],k = 1,n,rank[SZ];

bool cmp_sa(int i,int j)
{
    if(rank[i] != rank[j]) return rank[i] < rank[j];
    else
    {
        int x = i + k <= n ? rank[i + k] : -1;
        int y = j + k <= n ? rank[j + k] : -1;
        return x < y;
    }
}

void get_sa(char s[])
{
    for(int i = 0;i <= n;i ++)
    {
        sa[i] = i;
        rank[i] = i == n ? -1 : s[i];
    }
    for(k = 1;k <= n;k <<= 1)
    {
        sort(sa,sa + 1 + n,cmp_sa);

        tmp[sa[0]] = 0;
        for(int i = 1;i <= n;i ++)
            tmp[sa[i]] = tmp[sa[i - 1]] + (cmp_sa(sa[i - 1],sa[i]) ? 1 : 0);
        for(int i = 0;i <= n;i ++)
            rank[i] = tmp[i];
    }
}

void get_lcp(char s[])
{
    int h = 0;
    lcp[0] = 0;
    for(int i = 0;i <= n;i ++)
        rank[sa[i]] = i;
    for(int i = 0;i < n;i ++)
    {
        int j = sa[rank[i] - 1];
    //  cout<<"sa:"<<i<<" "<<j<<endl;
        if(h) h --;
        while(i + h < n && j + h < n)
        {
            if(s[i + h] == s[j + h]) h ++;
            else break;
        }
        lcp[rank[i] - 1] = h;
    }
}

LL ask()
{
    LL ans = 0;
    for(int i = 1;i <= n;i ++)
    {
        ans += n - sa[i] - lcp[i];
//      cout<<n - sa[i] - lcp[i]<<endl;
    }
    return ans;
}

void init()
{
    memset(sa,0,sizeof(sa));
    memset(lcp,0,sizeof(lcp));
    memset(rank,0,sizeof(rank));
    memset(tmp,0,sizeof(tmp));
}

char s[SZ];

int main()
{
    int T;
    scanf("%d",&T);
    while(T --)
    {
        init();
        scanf("%s",s);
        n = strlen(s);
        get_sa(s);
        get_lcp(s);
    /*  for(int i = 0;i <= n;i ++)
            printf("%d ",lcp[i]); puts("");
        for(int i = 0;i <= n;i ++)
            printf("%d ",sa[i]); puts("");*/
        printf("%lld\n",ask());
    }
    return 0;
}
/*
2
CCCCC
ABABA
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值