码迷,mamicode.com
首页 > 其他好文 > 详细

dtoj4429 字符串(string)

时间:2020-01-31 10:57:41      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:void   math   one   注意   ==   oid   sort   main   eve   

给定一个字符串 $S$,对于每一个 $ 0 \le i < \lvert S \rvert $,求

$$f(i)= \max\{ j \le i ~|~ \exists k,j \le k <i-j ~ \land~\ S[k-j \cdots k]= S[i-j \cdots i]\}$$

其中 $S[a \cdots b]$ 表示 $S$ 以 $a$ 开始,$b$ 结尾的长度为 $b- a + 1$ 的子串。对空集取 $\max$ 的结果为 $0$。

换句话说, 就是对每个 $i$,求一个最大的 $j$,使得 $S[i-j \cdots i]$ 是 $ S[0 \cdots i-j-1]$ 的子串。


Sol

建出sam.预处理每一个节点最早出现的位置。

注意到答案有单调性,我们可以每次从上一次的答案往这个字符c走一步,然后暴力往上跳同时判是否合法。

判断方法即该节点表示的串最早出现位置在 (i-该节点表示最短串长)之前。

技术图片
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#define maxn 2000005
using namespace std;
int n,rt,la,cnt,tax[maxn],ord[maxn];
char ch[maxn];
struct node{
    int par,Max,Min;
    int nex[2];
}s[maxn];
void ins(int c){
    int np=++cnt,p=la;la=np;s[np].Max=s[p].Max+1;s[np].Min=s[np].Max;
    for(;p&&!s[p].nex[c];p=s[p].par)s[p].nex[c]=np;
    if(!p)s[np].par=rt;
    else {
        int q=s[p].nex[c],nq;
        if(s[q].Max==s[p].Max+1)s[np].par=q;
        else {
            nq=++cnt;s[nq].Max=s[p].Max+1;s[nq].Min=1e9;
            for(int j=0;j<2;j++)s[nq].nex[j]=s[q].nex[j];
            s[nq].par=s[q].par;s[np].par=s[q].par=nq;
            for(;p&&s[p].nex[c]==q;p=s[p].par)s[p].nex[c]=nq;
        }
    }
}
void Sort(){
    for(int i=1;i<=cnt;i++)tax[s[i].Max]++;
    for(int i=1;i<=n;i++)tax[i]+=tax[i-1];
    for(int i=1;i<=cnt;i++)ord[tax[s[i].Max]--]=i;
}
int main(){
    scanf(" %s",ch+1);n=strlen(ch+1);
    rt=la=++cnt;
    for(int i=1;i<=n;i++)ins(ch[i]-0);
    Sort();
    for(int i=cnt;i>1;i--){
        int x=ord[i];
        s[s[x].par].Min=min(s[s[x].par].Min,s[x].Min);
    }
    int t=1;
    for(int i=1;i<=n;i++){
        t=s[t].nex[ch[i]-0];
        while(t!=rt){
            int f=s[t].par;
            if(i-s[f].Max-1>=s[t].Min)break;
            t=f;
        }
        printf("%d\n",min(i-s[t].Min,s[t].Max));
    }
    return 0;
}
View Code

 

dtoj4429 字符串(string)

标签:void   math   one   注意   ==   oid   sort   main   eve   

原文地址:https://www.cnblogs.com/liankewei/p/12244683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!