-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPattern Positions.cpp
99 lines (89 loc) · 2.26 KB
/
Pattern Positions.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <bits/stdc++.h>
using namespace std;
#define ll long long
struct SuffixAuto {
struct State {
int len, link;
int next[26];
State(int _len = 0, int _link = -1) : len(_len), link(_link) {
memset(next, -1, sizeof(next));
}
};
vector<State> states;
int last;
SuffixAuto() {}
SuffixAuto(const string &S) {
init(S);
}
inline int state(int len = 0, int link = -1) {
states.emplace_back(len, link);
return states.size() - 1;
}
void init(const string &S) {
states.reserve(2 * S.size());
last = state();
for (char c : S)
extend(c);
}
void extend(char _c) {
int c = _c - 'a'; // change for different alphabet
int cur = state(states[last].len + 1), P = last;
while (P != -1 && states[P].next[c] == -1) {
states[P].next[c] = cur;
P = states[P].link;
}
if (P == -1)
states[cur].link = 0;
else {
int Q = states[P].next[c];
if (states[P].len + 1 == states[Q].len)
states[cur].link = Q;
else {
int C = state(states[P].len + 1, states[Q].link);
copy(states[Q].next, states[Q].next + 26, states[C].next);
while (P != -1 && states[P].next[c] == Q) {
states[P].next[c] = C;
P = states[P].link;
}
states[Q].link = states[cur].link = C;
}
}
last = cur;
}
};
string S;
SuffixAuto sa;
ll dp[200005];
ll dfs(int u) {
if (dp[u] > 0)
return dp[u];
dp[u] = 0;
for (int i = 0; i < 26; i++)
if (sa.states[u].next[i] != -1)
dp[u] = max( dfs(sa.states[u].next[i]),dp[u]);
return dp[u] += 1;
}
void calcFirst(int n,string t){
int u = 0;
for(auto c:t){
if( sa.states[u].next[ c-'a' ] == -1 ){
cout<<-1<<endl;
return;
}
u = sa.states[u].next[ c-'a' ];
}
cout<<n-dp[u]-t.size()+2<<endl;
}
int main() {
cin >> S;
sa.init(S);
dfs(0);
int q;
cin>>q;
while(q--){
string t;
cin>>t;
calcFirst(S.size(),t);
}
//cout << dfs(0) - 1 << '\n';
}