Codeforces Beta Round #93 D. Password——后缀自动机

题意:找到一个字符串的最长的子串满足同时为该串的前缀,中缀和后缀。

按逆拓扑序更新每个状态最左出现和最右出现的位置和出现的次数,满足r[s] == len && l[s] - val[s] == 0 && num[s] > 2的所有状态中最长的为我们要的解。

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

const int maxn = 2000000 + 10;
char str[maxn / 2];
int len;
struct suffix_automaton
{
    int ch[maxn][26], pre[maxn], val[maxn];
    int l[maxn], r[maxn], num[maxn], c[maxn / 2], top[maxn];
    int sz, last;
    
    void init()
    {
        pre[0] = -1; last = 0; sz = 1;
        memset(ch[0], 0, sizeof(ch[0]));
        memset(num, 0, sizeof(num));
    }
    
    void insert(int x)
    {
        int p = last, np = sz++;
        last = np;
        memset(ch[np], 0, sizeof(ch[np]));
        val[np] = val[p] + 1;
        while(p != -1 && ch[p][x] == 0)
        {
            ch[p][x] = np;
            p = pre[p];
        }
        if(p == -1) pre[np] = 0;
        else
        {
            int q = ch[p][x];
            if(val[q] == val[p] + 1) pre[np] = q;
            else
            {
                int nq = sz++;
                memcpy(ch[nq], ch[q], sizeof(ch[q]));
                val[nq] = val[p] + 1;
                pre[nq] = pre[q];
                pre[q] = pre[np] = nq;
                while(p != -1 && ch[p][x] == q) { ch[p][x] = nq; p = pre[p]; }
            }
        }
    }
    
    void solve()
    {
        memset(c, 0, sizeof(c));
        for(int i = 0; i < sz; ++i) c[val[i]] += 1;
        for(int i = 1; i <= len; ++i) c[i] += c[i - 1];
        for(int i = 0; i < sz; ++i) top[--c[val[i]]] = i;
        for(int i = 0; i < sz; ++i) { l[i] = len + 1; r[i] = 0; }
        for(int i = 0; ; i = ch[i][str[val[i]] - 'a'])
        {
            l[i] = r[i] = val[i];
            num[i] = 1;
            if(val[i] == len) break;
        }
        for(int i = sz - 1; i > 0; --i)
        {
            int u = top[i];
            l[pre[u]] = min(l[pre[u]], l[u]);
            r[pre[u]] = max(r[pre[u]], r[u]);
            num[pre[u]] += num[u];
        }
        int ans = 0;
        for(int i = 1; i < sz; ++i)
            if(num[i] > 2 && r[i] == len)
                if(l[i] - val[i] == 0) ans = max(ans, val[i]);
        if(ans != 0)
            for(int i = len - ans; i < len; ++i)
                printf("%c", str[i]);
        else printf("Just a legend");
        printf("\n");
    }
    
}sam;

int main()
{
    freopen("in.txt", "r", stdin);
    scanf("%s", str); len = strlen(str); sam.init();
    for(int i = 0; i < len; ++i) { sam.insert(str[i] - 'a'); }
    sam.solve();
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值