summaryrefslogtreecommitdiff
path: root/string/suffixAutomaton.cpp
blob: 4d05b6e808349ef72497a4115ce8d6fafd62b980 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
constexpr char MIN_CHAR = 'a';
constexpr ll ALPHABET_SIZE = 26;
struct SuffixAutomaton {
	struct State {
		int length, link; 
		vector<int> next;
		State() : next(ALPHABET_SIZE) {}
	};
	vector<State> states;
	int size, last;

	SuffixAutomaton(const string &s) : states(2*sz(s)) {
		size = 1; last = 0;
		states[0].link = -1;
		for (auto c : s) extend(c - MIN_CHAR);
	}

	void extend(int c) {
		int current = size++;
		states[current].length = states[last].length + 1;
		int pos = last;
		while (pos != -1 && !states[pos].next[c]) {
			states[pos].next[c] = current;
			pos = states[pos].link;
		}
		if (pos == -1) states[current].link = 0;
		else {
			int q = states[pos].next[c];
			if (states[pos].length + 1 == states[q].length) {
				states[current].link = q;
			} else {
				int clone = size++;
				states[clone].length = states[pos].length + 1;
				states[clone].link = states[q].link;
				states[clone].next = states[q].next;
				while (pos != -1 && states[pos].next[c] == q) {
					states[pos].next[c] = clone;
					pos = states[pos].link;
				}
				states[q].link = states[current].link = clone;
		}}
		last = current;
	}

	// Pair with start index (in t) and length of LCS.
	pair<int, int> longestCommonSubstring(const string &t) {
		int v = 0, l = 0, best = 0, bestpos = 0;
		for (int i = 0; i < sz(t); i++) {
			int c = t[i] - MIN_CHAR;
			while (v && !states[v].next[c]) {
				v = states[v].link;
				l = states[v].length;
			}
			if (states[v].next[c]) {v = states[v].next[c]; l++;}
			if (l > best) {best = l; bestpos = i;}
		}
		return {bestpos - best + 1, best};
	}

	// Returns all terminals of the automaton.
	vector<int> calculateTerminals() {
		vector<int> terminals;
		int pos = last;
		while (pos != -1) {
			terminals.push_back(pos);
			pos = states[pos].link;
		}
		return terminals;
	}
};