SAM模板

luogu P3804 为例

感觉我对 SAM 理解的不是很透彻。

#include <cstdio>
#include <cstring>
#define R register
#define Null b
#define Max(_A, _B) (_A > _B ? _A : _B)
char s[1000010];
struct Data
{
    int len, size, In;
    Data *ch[26], *pre;
} b[2000010], *last = b, *Q[2000010], **head = Q, **tail = Q;
int tot;
void Add(R int s)
{
    R Data *cur = b + ++tot, *p = last, *q;
    cur->len = last->len + 1;
    while(p && !p->ch[s]) p->ch[s] = cur, p = p->pre;
    if(p == 0) cur->pre = Null;
    else
    {
        q = p->ch[s];
        if(q->len == p->len + 1) cur->pre = q;
        else
        {
            R Data *clone = b + ++tot; *clone = *q;
            clone->len = p->len + 1;
            cur->pre = q->pre = clone;
            clone->size = 0;
            while(p && p->ch[s] == q)
            {
                p->ch[s] = clone;
                p = p->pre;
            }
        }
    }
    cur->size = 1; //只有原有的点有 size
    last = cur;
}
long long Ans;
int main()
{
    scanf("%s", s + 1);
    for(R int i = 1; s[i]; i++) Add(s[i] - 'a');
    for(R Data *i = b + 1; i <= b + tot; i++) i->pre->In++; b[0].In = 19260817;
    for(R Data *i = b + 1; i <= b + tot; i++) if(!i->In) *(++tail) = i;
    do
    {
        ++head;
        (*head)->pre->In--;
        if((*head)->pre->In == 0) *(++tail) = (*head)->pre;
        (*head)->pre->size += (*head)->size;
        if((*head)->size > 1) Ans = Max(1ll * (*head)->size * (*head)->len, Ans);
    }
    while(head < tail);
    printf("%lld\n", Ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/steaunk/article/details/79427187
SAM