Skip to content

Commit

Permalink
Create suffix.automaton.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
vmartinv committed Feb 12, 2016
1 parent b495fba commit afd02f8
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions string/suffix.automaton.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#include <bits/stdc++.h>
using namespace std;
#define dprint(v) cerr << #v"=" << v << endl //;)
#define forr(i,a,b) for(int i=(a); i<(b); i++)
#define forn(i,n) forr(i,0,n)
#define dforn(i,n) for(int i=n-1; i>=0; i--)
#define forall(it,v) for(typeof(v.begin()) it=v.begin();it!=v.end();++it)
#define sz(c) ((int)c.size())
#define zero(v) memset(v, 0, sizeof(v))
#define pb push_back
#define fst first
#define snd second
typedef long long ll;
typedef pair<int,int> ii;

struct St {
int len;
St *link;
map<char,St*> next;
St(int len, St* link=NULL):len(len),link(link){}
};
struct SuA{
St *init, *last;
SuA(): init(new St(0)), last(init) {}
void extend(char c){
St *cur=new St(last->len+1, init), *p=last;
for(;p && !p->next.count(c); p=p->link) p->next[c]=cur;
if(p){
St *q=p->next[c];
if(p->len+1==q->len) cur->link=q;
else{
St *clone = new St(p->len+1, q->link);
clone->next = q->next;
for(;p && p->next.count(c) && p->next[c]==q; p=p->link)
p->next[c] = clone;
q->link = cur->link = clone;
}
}
last = cur;
}
}aut;


int main() {
string s; cin >> s;
aut=SuA();
forn(i, sz(s)) aut.extend(s[i]);
return 0;
}

0 comments on commit afd02f8

Please sign in to comment.