Skip to content

Commit

Permalink
后缀自动机(未验证正确性)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dev-XYS committed Feb 17, 2017
1 parent 847ca7a commit ec3a135
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions Suffix-Automaton.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#include <cstdio>
#include <cstring>

#define NIL 0
#define ALPHABET_SIZE 26

using namespace std;

struct node
{
node *next[ALPHABET_SIZE], *parent;
int len;
node(int _len = 0) : len(_len) { memset(next, 0, sizeof(next)), parent = NIL; }
}*root, *last;

char s[100000];
int len;

void init()
{
root = new node(0);
last = root;
}

void extend(int x)
{
node *p = last;
node *np = new node(p->len + 1);
while (p != NIL && p->next[x] == NIL)
{
p->next[x] = np;
p = p->parent;
}
if (p == NIL)
{
np->parent = root;
}
else
{
node *q = p->next[x];
if (q->len == p->len + 1)
{
np->parent = q;
}
else
{
node *nq = new node;
*nq = *q;
nq->len = p->len + 1;
q->parent = np->parent = nq;
while (p != NIL && p->next[x] == q)
{
p->next[x] = nq;
p = p->parent;
}
}
}
last = np;
}

int main()
{
scanf("%s", s);
len = strlen(s);
init();
for (int i = 0; i < len; i++)
{
extend(s[i] - 'a');
}
return 0;
}

0 comments on commit ec3a135

Please sign in to comment.