CF961F k-substrings

题意

给定一个字符串 S S
求所有的 S[i,ni+1] border b o r d e r 长度(最长的前缀等于后缀),要求长度是奇数
n106 n ≤ 10 6

Sol

首先发现每次求的串都是原串去掉前后 i1 i − 1 位得到的串
一个套路,把串翻折,又因为 border b o r d e r 长度可能大于一半,所以我们把串倍长后翻折
也就是翻转过来隔空插入在一起
例如:
bcabcabcabcabca b c a b c a b c a b c a b c a
翻转后 acbacbacbacbacb a c b a c b a c b a c b a c b
隔一个插入在一起 baccabbaccabbaccabbaccabbaccab b a c c a b b a c c a b b a c c a b b a c c a b b a c c a b
那么也就是求这个串的以某个位置的开始的最长回文串
又因为得到的这个串本身就是回文串,所以并不用翻转过来,直接求以某个位置的结束的最长回文串就好了
比如 baccab b a c c a b 就是 S[1,3] S [ 1 , 3 ] S[13,15] S [ 13 , 15 ]
回文树就好了

注意到每次都要跳 fail f a i l 链跳到满足要求的位置,而每次都跳很耗时
如果之后跳到之前跳到过的点,就可以直接跳到之前跳到的对答案有贡献的点上
再继续跳
并查集维护一下就好了

# 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;

IL int Input(){
    RG int x = 0, z = 1; RG char c = getchar();
    for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
    for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
    return x * z;
}

const int maxn(2e6 + 5);

int n, last, tot, anc[maxn], id[maxn];
int len[maxn], first[maxn], nxt[maxn], type[maxn], fa[maxn];
char s[maxn], str[maxn];

IL int Son(RG int u, RG int c){
    for(RG int v = first[u]; v; v = nxt[v])
        if(type[v] == c) return v;
    return 0;
}

IL void Link(RG int u, RG int v, RG int c){
    nxt[v] = first[u], first[u] = v, type[v] = c;
}

IL void Extend(RG int pos, RG int c){
    RG int p = last;
    while(s[pos - len[p] - 1] != s[pos]) p = fa[p];
    if(!Son(p, c)){
        RG int np = ++tot, q = fa[p];
        while(s[pos - len[q] - 1] != s[pos]) q = fa[q];
        len[np] = len[p] + 2, fa[np] = Son(q, c);
        Link(p, np, c);
    }
    last = Son(p, c);
}

IL int Find(RG int x){
    return anc[x] == x ? x : anc[x] = Find(anc[x]);
}

int main(){
    Fill(type, -1), n = Input(), scanf(" %s", str + 1);
    for(RG int t = 0, i = 1, j = n; j; ++i, --j)
        s[++t] = str[i], s[++t] = str[j];
    tot = 1, fa[0] = fa[1] = 1, len[1] = -1, n <<= 1, anc[0] = 1;
    for(RG int i = 1; i <= n; ++i) Extend(i, s[i] - 'a'), id[i] = last;
    for(RG int i = 0; i <= tot; ++i) anc[i] = i;
    for(RG int i = 1, m = n >> 1, t = (m + 1) >> 1; i <= t; ++i){
        RG int x = Find(id[n - ((i - 1) << 1)]);
        while(x != 1 && ((len[x] >> 1) >= (m - ((i - 1) << 1)) || len[x] % 4 != 2)) x = anc[x] = Find(fa[anc[x]]);
        printf("%d ", (len[x] % 4 == 2) ? (len[x] >> 1) : -1);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值