[SPOJ]DISUBSTR:Distinct Substrings&[SPOJ]SUBST1:New Distinct Substrings

题面

Vjudge
Vjudge

Sol

求一个串不同子串的个数
每个子串一定是某个后缀的前缀,也就是求所有后缀不同前缀的个数
每来一个后缀 suf(i) s u f ( i ) 就会有, lensa[i]+1 l e n − s a [ i ] + 1 的新的前缀,又由于有 height h e i g h t 个重复的,那么就是 lensa[i]+1height l e n − s a [ i ] + 1 − h e i g h t 的贡献
两个就只有数组大小的区别

# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1010);

int n, a[_], sa[_], rk[_], tmp[_], height[_], t[_], mx, T;
char s[_];

IL bool Cmp(RG int x, RG int y, RG int k){  return tmp[x] == tmp[y] && tmp[x + k] == tmp[y + k];  }

IL void Suffix_Sort(){
    RG int m = mx;
    for(RG int i = 0; i <= m; ++i) t[i] = 0;
    for(RG int i = 1; i <= n; ++i) ++t[rk[i] = a[i]];
    for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
    for(RG int i = n; i; --i) sa[t[rk[i]]--] = i;
    for(RG int k = 1; k <= n; k <<= 1){
        RG int l = 0;
        for(RG int i = n - k + 1; i <= n; ++i) tmp[++l] = i;
        for(RG int i = 1; i <= n; ++i) if(sa[i] > k) tmp[++l] = sa[i] - k;
        for(RG int i = 0; i <= m; ++i) t[i] = 0;
        for(RG int i = 1; i <= n; ++i) ++t[rk[tmp[i]]];
        for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
        for(RG int i = n; i; --i) sa[t[rk[tmp[i]]]--] = tmp[i];
        swap(rk, tmp); rk[sa[1]] = l = 1;
        for(RG int i = 2; i <= n; ++i) rk[sa[i]] = Cmp(sa[i - 1], sa[i], k) ? l : ++l;
        if(l >= n) break;
        m = l;
    }
    for(RG int i = 1, h = 0; i <= n; ++i){
        if(h) --h;
        while(a[i + h] == a[sa[rk[i] - 1] + h]) ++h;
        height[rk[i]] = h;
    }
}

IL int Calc(){
    RG int ans = n - sa[1] + 1;
    for(RG int i = 2; i <= n; ++i) ans += n - sa[i] + 1 - height[i];
    return ans;
}

int main(RG int argc, RG char* argv[]){
    scanf("%d", &T);
    while(T--){
        scanf(" %s", s + 1);
        n = strlen(s + 1); mx = 0;
        for(RG int i = 1; i <= n; ++i) a[i] = s[i], mx = max(mx, a[i]);
        Suffix_Sort();
        printf("%d\n", Calc());
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值