We are given a string S of length up to 1e5. Also given N (up to 1e5) strings p_i. The total length sum of p_i is <= 1e5.
We can perform operation: choose exactly one character in S and replace it with '*'. (The asterisk character is considered a special replacement; but we treat it as a character that is not a lowercase letter, so it will break any substring that includes it. It is effectively a "censored" character that makes any substring containing it different from any p_i (since p_i consist only of lowercase letters). But note: the condition is: For all pairs (S_{ij}, p_k), it must hold that S_{ij} != p_k. That is, for every contiguous substring of S (including length 1? Yes, any i <= j) and for every p_k, the substring must not equal p_k. So we must ensure that no forbidden word p_k appears as a substring of the final S after replacements.
We can replace characters with '', which will certainly break substrings that include that position because '' is not a lowercase letter. However, note that if we replace a character with '', then any substring that includes that position will contain '', and thus cannot equal any p_k because p_k consist only of lowercase letters. So effectively, we are allowed to "break" appearances of forbidden substrings by placing '' characters at some positions. We need to find the minimum number of positions to change to '' such that the resulting string contains no occurrence (as contiguous substring) of any p_i.
This is a classic problem: given a set of forbidden patterns, we need to cover all occurrences (overlapping also) by selecting positions to delete (or change to '') such that each occurrence is covered. This is a hitting set problem on intervals. Each occurrence of any pattern in the string is an interval [l, r] (positions where the pattern appears). By placing a '' at any position in that interval, the occurrence is "destroyed" because the substring now contains ''. However, careful: if we put '' at position p within the interval, the substring from l to r will contain '*', thus not equal to the pattern. So indeed, each occurrence can be "blocked" by selecting at least one position in its interval.
We need to choose minimum number of positions such that each occurrence interval contains at least one chosen position. However, note that occurrences may be overlapping. This is a classic problem of minimum points to stab all intervals (the interval covering/hitting set problem). For a set of intervals on a line, the minimum number of points needed to intersect all intervals is equal to the maximum size of a set of pairwise disjoint intervals (by the interval stabbing / interval scheduling duality). The greedy algorithm: sort intervals by right endpoint, then repeatedly place a point at the rightmost possible to cover as many as possible.
But careful: There is nuance: If we place a '', it will break all occurrences that include that position. However, is it possible that placing a '' at a position might not be enough to break some occurrence if that occurrence does not include that position? No, only those intervals that include that point. So we need to stab all intervals.
Thus, the problem reduces to: given S and set of patterns, find all occurrences (starting positions) of each pattern in S (overlaps allowed). For each occurrence, we have interval [start, start+len-1] (1-indexed). Then we need minimum number of points to stab all intervals. However, note that the total number of occurrences could be huge (up to O(|S| * max pattern length) maybe). But total pattern lengths sum to 1e5 and |S| up to 1e5. So we need to efficiently compute all occurrences, but the naive matching could be large. However, the sum of lengths is bounded, so using Aho-Corasick automaton we can find all matches in O(|S| + total output) time, where total output is total number of occurrences. But total output could be up to O(|S| * number of patterns) in worst-case? Let's analyze: Given many patterns, the total occurrences could be as high as O(|S| * sqrt(total length)? Actually, consider many patterns that are all "a". The total length sum is 1e5, so number of patterns N could be up to 1e5, each pattern "a". Then occurrences: each pattern "a" appears at each position in S (if S is all 'a'). So total occurrences = |S| * N, which could be up to 1e10, too many. But constraints: sum of lengths of patterns is ≤ 1e5, but the number of patterns can be large with short lengths. Could the number of occurrences be huge? Yes, if many patterns are single characters. For example, S length 1e5 all 'a', and patterns: N=1e5 all "a" (different? but it says if i ≠ j, p_i ≠ p_j; they are distinct, but they could all be "a"? No, if they are distinct, they cannot all be "a". So they must be distinct strings. So all patterns "a" is not allowed because they would be identical. However, they could be "a", "aa", "aaa", etc. But if they are all distinct but possibly overlapping, we could have many patterns that are substrings of a uniform string. For example, S = all 'a's length L=1e5. Patterns: all strings "a", "aa", "aaa", ... up to length L? But total length sum is limited to 1e5, so the maximum number of patterns if each has average length L_avg, the number is N ≤ sum lengths ≤ 1e5. But if they are distinct, could there be many patterns that are all substrings of a uniform string? For example, patterns: "a", "aa", "aaa", ..., "a^k" for k up to 1e5? The sum of lengths would be about k(k+1)/2 ~ 5e9 if k=1e5, far exceeding 1e5. So not possible. So total number of patterns is bounded by total length sum, but also each pattern length could be 1. The maximum number of patterns of length 1 is number of distinct letters? There are only 26 lowercase letters. So you can't have more than 26 distinct patterns of length 1. So if patterns are distinct, the maximum number of patterns of length 1 is 26. So the number of patterns is limited by 26 for length 1, for length 2 there are at most 26^2 = 676 distinct strings, but sum of lengths constraint would then be at most 26^2 * 2 = 1352 which is small. But you could have patterns of various lengths, but total length sum is ≤ 1e5, so the number of patterns is at most 1e5 (if all length 1, but distinctness limits to 26). So effectively, N could be up to 1e5 but only if patterns are longer. The total occurrences could be large still? Let's think: if we have many patterns, each pattern can occur many times. For example, S length 1e5, patterns: suppose we have 100 patterns each of length 10, and S is random; each could appear many times. But worst-case could be if S is all 'a's and patterns are many distinct strings of 'a' with lengths up to maybe 1000? But total length sum is 1e5, so if we have 100 patterns of length 1000, sum lengths = 100000, occurrences: each pattern of length L occurs at each starting position up to |S|-L+1, which for L=1000 gives about 99000 occurrences per pattern. 100 * 99000 ~ 9.9e6, which is maybe acceptable if we output them? 10 million could be okay? But 1e5 patterns of average length 1? can't due to distinctness. The worst-case number of occurrences might be on the order of |S| * (number of patterns) but number of patterns limited by total length sum? Not directly; if patterns are very short, there are few distinct patterns; if patterns are long, occurrences per pattern are limited because the pattern length reduces number of possible positions. Let's try to bound total occurrences more formally. For each pattern p, its occurrences in S can be found via Aho-Corasick; but total number of matches reported by Aho-Corasick is O(|S| + total output). We need to bound total output in terms of total length sum and |S|. In worst-case, consider S = all 'a's length L. Patterns: Suppose we take all distinct strings over alphabet 'a' only? But they must be distinct, and total sum of lengths = M. If we take patterns as "a", "aa", "aaa", ... up to length K such that sum of lengths = K(K+1)/2 ≤ M, then K ~ sqrt(2M). So number of patterns ~ sqrt(2M). For M=1e5, K ~ 447. So about 447 patterns. Occurrences: each pattern of length l occurs L-l+1 times. So total occurrences = sum_{l=1}^{K} (L - l + 1) ≈ K1e5 - ~1e5 ≈ 4.47e7. That's 44.7 million, which might be borderline but possibly okay if we process efficiently and do interval stabbing. However, typical contest constraints with 1e5 might allow up to maybe 1e7 or 2e7 operations with optimized C++ but Python might struggle. But we need to design algorithm in Python? The problem is from AtCoder? Probably AtCoder typical constraints 1e5, and Python solution can pass with Aho-Corasick and interval greedy. But 44 million intervals is too many for Python; we need to think about optimization. Possibly there is a more clever way: The intervals are all occurrences of patterns. The stabbing minimum points can be computed without explicitly listing all intervals if we treat them as "forbidden substrings" and we need to cover them. Could we compute the minimum number of replacements by DP? This is like: we need to select positions to change to '*' to avoid any forbidden substring. That's similar to "string censorship" problems: given forbidden words, you want to block them by marking positions. It is similar to classic problem: given a set of patterns, find minimum number of characters to delete (or replace) such that the resulting string contains no pattern as a substring. That is like "find minimum vertex cover in interval graph" which can be solved by greedy algorithm if we know intervals. But we need intervals.
But maybe we can compute the minimal number of positions using DP with Aho-Corasick automaton? Since we can think of scanning S and maintaining states, and we need to avoid reaching any state that corresponds to a pattern (i.e., terminal state). The operation of replacing a character with '' essentially "resets" the automaton because '' is not in alphabet; maybe it breaks the continuity. Actually, if we replace a character with '', then any substring crossing that position is invalid, so we can treat that as a "reset": after a '', we cannot have a pattern crossing it. However, patterns could start after the ''. So we need to decide positions to set to '' to ensure that after processing the whole string, we never have a pattern as a substring. This is similar to "String segmentation with forbidden substrings" but we can break with special chars.
Alternate viewpoint: We want to select a set of positions to change such that the remaining string (with '' considered as a barrier) has no forbidden substring. Because '' is not a lowercase letter, it effectively splits the string into segments of lowercase letters between '' characters. In each segment, we must ensure that no forbidden pattern appears entirely within that segment. So we need to choose positions to insert '' (or change to '') to break the string into segments where each segment is "clean" (no forbidden substring). The problem then becomes: given a string S, we can insert '' (by replacing characters) at some positions; after insertion, the string becomes a sequence of blocks of original characters separated by ''; we need that each block contains no forbidden substring. The goal is to minimize number of '' inserted.
This is reminiscent of the classic problem of covering all occurrences with a minimum number of points, which indeed corresponds to placing '' at those points to break all occurrences. Since each '' can break many occurrences, the greedy algorithm on intervals gives the minimum number of points.
Thus, we need to compute intervals (occurrences) and then solve minimum stabbing.
But the number of intervals might be large. However, note that intervals are defined by pattern occurrences. The greedy algorithm on intervals can be performed without enumerating all intervals if we can compute the "rightmost" needed point. But we need to know the intervals. Alternatively, we can think of it as: we scan from left to right, and whenever we encounter a pattern ending at position i (i.e., there is an occurrence ending at i), we may need to place a '*' at that position to cover all intervals that end at i and have not been covered yet. That's exactly the greedy algorithm: sort intervals by ending position; then pick the endpoint of the earliest finishing interval that is not yet covered, place a point at its end, and cover all intervals that include that point. So we only need to know, for each position, the earliest ending of an uncovered interval. But we need to know intervals as we scan? Typically, the greedy algorithm processes intervals sorted by end. So we need all intervals, or at least we need to know the intervals in order of their end positions.
But perhaps we can compute, for each ending position, the longest pattern that ends there? Not exactly. The greedy algorithm would: iterate over positions from left to right, maintain the "furthest left" uncovered interval's end. But perhaps we can simulate the greedy using the automaton and a pointer to the earliest start of an occurrence that is not yet covered? Let's think.
We have intervals that may overlap. The greedy algorithm:
- sort intervals by their right endpoint (end position).
- Initialize last_covered = 0 (or -inf) representing that we have placed a point at some position and all intervals with start <= that point are covered.
- For each interval in sorted order by end:
- if its start > last_covered (i.e., not covered by previous point), then we need to place a new point at its end, set last_covered = end.
Thus, the answer is the number of points placed.
Now, note that intervals are all occurrences. Many intervals share the same end. But if we have many intervals, some will be covered by earlier points.
Maybe we can avoid enumerating all intervals if we can determine, for each position as we scan left to right, whether there exists an occurrence that ends at this position and whose start is after the last placed point. If yes, we need to place a point at this position.
This is reminiscent of the "minimum number of deletions to avoid forbidden substrings" problem: we can scan and when we detect a forbidden substring, we can delete (or replace) the last character. That is similar to the classic problem of removing minimal characters to avoid bad words, which uses a greedy that places deletion at the end of the substring when detected. For example, in "brainfuck" with pattern "fuck", scanning: we keep building a suffix that could match a pattern. When we fully match a pattern, we increment answer and reset the suffix (like delete the last character). But careful: In the classic problem, we are allowed to delete characters (or replace) to prevent any occurrence; often the greedy solution is: traverse S, maintain the longest suffix that is a prefix of any pattern (using Aho-Corasick). When we reach a state that is terminal (i.e., a pattern ends), we increment count (meaning we delete the current character or the whole pattern?) Actually there is a known problem: "Given a string and a set of forbidden substrings, find the minimum number of characters to delete so that the resulting string does not contain any forbidden substring." The typical greedy solution: use a stack and Aho-Corasick. As we scan characters, we push onto stack and update automaton state. When we reach a terminal state (meaning the current suffix forms a forbidden word), we then pop the length of that word (i.e., delete that substring) and increment the deletion count by the length? Or sometimes we delete just one character? That is different.
In our problem, we can replace with '', which is like "deleting" that character from the perspective of breaking substrings. But note: Replacing a character with '' only affects substrings that include that character. In the greedy algorithm for interval covering, we place a point at the end of an interval that is not yet covered. That means we are essentially "covering" the interval by placing '' at its last character. So when we encounter an occurrence that is not covered, we place '' at its ending position. That would break that occurrence and any overlapping ones that include that position.
Could we simulate that by scanning with Aho-Corasick and maintaining the last position where we placed a '*'? Let's try.
Let last_placed = 0 (the index of the last placed '' character; initially 0 meaning no character replaced before start). While scanning from left to right (i=1..|S|), we need to know if there exists any occurrence of a forbidden pattern that ends at i and starts after last_placed. Because if such an occurrence exists, then that interval is not covered by any previous ''. Then we need to place a '*' at i. After placing at i, we set last_placed = i, and all intervals that include i are covered, so we can continue.
But careful: The greedy algorithm for intervals sorted by end says: when we encounter an interval (l, r) with l > last_placed, we place at r and set last_placed = r. This is equivalent to: as we iterate over positions in increasing order of r, we decide to place a point at r if there exists any interval ending at r whose l > last_placed. However, we also need to consider that multiple intervals may end at the same r. The condition is: if there exists any interval with l > last_placed, we place a point at r. Because if there is at least one uncovered interval ending at r, we must cover it; the greedy places at r and that covers all intervals containing r, including those with l <= last_placed (but they are already covered) and those with l > last_placed. So yes, decision at each ending position r is: if max(l among intervals ending at r) > last_placed? Actually, we need to know if any interval with l > last_placed exists. So we need to know the maximum start (or all starts) of intervals ending at r. If the maximum start > last_placed, then there is an uncovered interval.
But also, we must consider intervals that end later but start before last_placed? Those are covered. So this approach works if we can compute, for each position r, the maximum l (i.e., the latest start) among all occurrences ending at r. Actually we need to know if there exists an occurrence with start > last_placed. Equivalent to: let max_start_at_r = max{ l | there is an occurrence [l, r] }. Then if max_start_at_r > last_placed, we need to place at r. But is that sufficient? Let's test: Suppose there is an occurrence ending at r1 with l1 > last_placed. Then we place at r1. Now last_placed = r1. Now consider later positions. Intervals that end after r1 and have start <= r1 are covered? They contain r1? Not necessarily. If an interval [l, r] with r > r1, does it contain r1? Only if l <= r1 <= r. But if l <= r1 <= r, then yes it contains r1 and thus is covered. But if l > r1, then it does not contain r1 and is uncovered. So our algorithm would then later at its end r if l > last_placed then place again. So indeed, we only need to know for each end position the maximum start among intervals ending there. However, careful: There might be intervals that start after last_placed but end before the current r? But we process in increasing r. So when we are at position r, we have already processed all earlier ends. So the only intervals that could still be uncovered are those that end at or after current position. So we can process ends in increasing order.
Thus, if we can compute for each position r (1-indexed) the maximum start among all occurrences that end at r, we can simulate:
last = 0
ans = 0
for r in 1..|S|:
if max_start_at[r] > last:
ans += 1
last = r
At the end, ans is the minimum number of points.
But is this correct? Let's verify with examples.
Example 1: S = brainfuck, pattern "fuck". Occurrences: "fuck" at positions? S indices: 1 b,2 r,3 a,4 i,5 n,6 f,7 u,8 c,9 k. "fuck" length 4, starts at 6, ends at 9. So max_start_at[9] = 6. Others are maybe 0 (or -inf). Process:
r=1..5: max_start_at=0 <= last(0) => no.
r=6: maybe no occurrence ending at 6? max_start_at[6] maybe 0.
r=7: 0, r=8:0, r=9:6 >0 => ans=1, last=9. Done. answer=1.
Example 2: S="aaa", pattern "a". Occurrences: at positions 1 (end 1), 2 (end 2), 3 (end 3). So max_start_at[1]=1, [2]=2, [3]=3.
Process:
r=1: max_start=1 > last(0) => ans=1, last=1.
r=2: max_start=2 > last(1) => ans=2, last=2.
r=3: max_start=3 > last(2) => ans=3, last=3. answer=3.
Example 3: S="hellshakeyano", patterns: "hell", "shake", "key". Let's find occurrences:
- "hell": starts at 1? h e l l -> positions 1-4: hell, ends at 4. Also maybe other? Only one.
- "shake": starts at 4? Actually "shake": s h a k e? Let's see: S: h e l l s h a k e y a n o. indices:1 h,2 e,3 l,4 l,5 s,6 h,7 a,8 k,9 e,10 y,11 a,12 n,13 o. "shake": s(5) h(6) a(7) k(8) e(9) -> start 5, end 9.
- "key": k e y? Actually "key": k e y? Positions: k at 8? e at 9, y at 10 -> start 8, end 10.
Also possible "key" starting at other? maybe not.
So occurrences: [1,4], [5,9], [8,10]. Compute max_start_at:
r=4: max_start=1
r=9: max_start=5? also maybe other? But there is also occurrence [5,9] and maybe? Also check if "hell" appears elsewhere? no.
r=10: max_start=8.
Now process:
last=0
r=1,2,3: no max_start (0)
r=4: max_start=1 >0 => ans=1, last=4
r=5-8: no max_start? Actually at r=5? No occurrence ending at5. r=6,7,8? r=8: maybe no occurrence ending? "key" ends at10, "shake" ends9. So no.
r=9: max_start=5 >4 => ans=2, last=9
r=10: max_start=8 >9? 8 >9 false (8 <=9) => not new. So answer=2. matches.
Thus the algorithm works.
But is it always correct? Let's consider overlapping intervals more complex. The greedy algorithm on intervals sorted by end says: if we process intervals in order of end, we place a point at the end of the first interval whose start > last_placed. That point is the end of that interval. Our simulation that checks at each end position r if max_start_at[r] > last_placed is equivalent because among all intervals ending at r, the one with the largest start is the "most restrictive" (hardest to cover). If its start > last_placed, then there exists an interval ending at r that is uncovered. However, could there be a scenario where an interval ending at r with start > last_placed exists, but the greedy algorithm would not place at r because a later interval with earlier end? Wait we process in order of increasing r. At point r, we consider all intervals ending at r. The greedy algorithm would consider intervals sorted by end. Suppose there are multiple intervals ending at r. The one with smallest start might be covered, but one with larger start might be uncovered. According to the greedy algorithm, when we process intervals in order of end, as soon as we encounter an interval with start > last_placed, we place at its end (which is r). So indeed, if any interval ending at r has start > last_placed, then the first such interval (the one with smallest end among uncovered) would be exactly at r (since we are scanning ends increasing). So we should place at r. So checking max_start_at[r] > last_placed is correct.
But wait: Could there be an interval that ends later but we might want to place earlier? The greedy algorithm ensures minimum points by placing at the end of the earliest-ending uncovered interval. So scanning ends increasing and placing when needed is exactly the greedy algorithm. So the algorithm is correct.
Now we need to compute, for each end position r (1-indexed), the maximum start (i.e., the latest start) among all occurrences ending at r. Because if we know that, we can run the simple O(|S|) scan.
Thus the core challenge is to compute for each position r in S, the maximum starting index of any pattern that ends exactly at r. If multiple patterns have different lengths, we need to consider all occurrences.
Now we need to efficiently compute these max_start values. Given the set of patterns, we can build an Aho-Corasick automaton. Then we traverse S, maintaining the current state. At each position i (1-indexed), we are at state corresponding to the suffix ending at i. In Aho-Corasick, each state may have output (patterns that end at this state). The patterns that end at position i are those whose length equals the depth from root to that state (but careful: because of failure links, a state may represent multiple patterns that end at that position, including those that are suffixes of the current matched string). In Aho-Corasick, as we process character S[i], we move to next state. Then we can iterate over the output of that state (which may be pattern IDs). For each pattern that ends at i, we know its length L. So its start = i - L + 1. So we can compute max_start_at[i] as max over all such patterns' start. But we need the maximum start (i.e., the latest start, which corresponds to the shortest pattern? Actually start = i - L + 1, so for a given i, larger start means smaller L? Let's see: for fixed i, start = i - L + 1, so larger start means smaller L (since L = i - start +1). So the maximum start corresponds to the pattern with smallest length among those ending at i? Not exactly; it's the pattern that starts as late as possible, i.e., the shortest pattern that ends at i. But we need the maximum start over all patterns ending at i. This is simply i - (minimum length among patterns ending at i) + 1? Wait: if we have multiple patterns ending at i, their lengths vary. The start is i - length + 1. So the maximum start corresponds to the pattern with the minimum length. Because larger start means start closer to i. So max_start = i - min_len + 1, where min_len is the minimum length among all patterns that end at i. However, it's not exactly that if we have multiple patterns with same length? That's fine.
But careful: There may be patterns that are suffixes of each other. In Aho-Corasick, the state may have output of multiple patterns, possibly of different lengths. So we can compute for each i the minimum length among patterns that end at i. Then max_start_at[i] = i - min_len + 1 if there is any pattern; else 0 (or -inf). Actually we need the maximum start; if no pattern ends at i, we can set max_start_at[i] = 0 (since last_placed is index of last placed point; indices start from 1; last_placed = 0 initially). But note: start indices are >=1. So if no pattern ends at i, we set to 0 (or a value <=0). Since last_placed is also an index, we compare >.
Thus, we need to compute for each position i, the minimum length among all patterns that end at i. But is it sufficient to take the minimum length? Because we need maximum start, which is indeed i - min_len + 1. However, is it possible that a pattern ending at i but with longer length (hence earlier start) could affect the greedy decision? In our algorithm we only care about max_start_at[i]. If there is an occurrence with start > last_placed, then we need to place a point at i. The occurrence with the largest start is the one that is hardest to cover (most likely to be uncovered). So indeed we only need the maximum start, which corresponds to the pattern with smallest length among those ending at i. But wait: what if there are patterns that end at i but with different lengths, the one with smallest length gives the largest start. So yes, we only need the minimal length among patterns ending at i.
But is there any nuance: Could there be an occurrence that ends at i but its start is not the maximum start among all occurrences ending at i, but it is still uncovered while the maximum start is covered? That's not possible: if the maximum start > last_covered, then there exists an uncovered interval. If the maximum start ≤ last_covered, then all starts ≤ last_covered, so all intervals ending at i are covered. So checking max_start is sufficient.
Thus, we can compute for each i, min_len_end[i] = minimum length of pattern that ends at i, if any; else INF.
Then we can run the greedy.
Now the main challenge: computing min_len_end efficiently for all i using Aho-Corasick. While traversing S, at each position we are at some state. This state may have output patterns (maybe multiple). We need to know, among all patterns that are suffixes of the current matched prefix (i.e., those that end at current position), what is the minimum length. In Aho-Corasick, each state typically stores a list of pattern IDs that end at that state, or a flag indicating a pattern ends. However, due to failure links, we also need to consider patterns that end at states reachable via failure links, because those correspond to patterns that are suffixes of the current string. So we need to aggregate the minimum pattern length over all output reachable from the current state via failure chain.
Standard approach: While building automaton, for each state we can compute "output length" as the minimum length among patterns that end at this state or any state reachable via failure links (or we can propagate via BFS). In many problems, we precompute for each state the shortest pattern that ends at that state or any of its failure ancestors. Then during scanning, at each position i we get the state, and we can quickly obtain the shortest pattern length that ends at that position. This is exactly what we need: min_len_end[i] = that shortest length.
So we can build Aho-Corasick with:
- nodes, each with children for 26 letters, failure link, and
shortest_output_length (or min_len), initially INF.
- When inserting a pattern, at its terminal node, we update its
min_len with the length of the pattern (maybe multiple patterns could end at same node, we take min).
- After building failure links (via BFS), we propagate: for each node in BFS order (starting from root and its children), we set node.min_len = min(node.min_len, failure_node.min_len). Actually careful: If a node itself has a pattern ending, its min_len is set to pattern length. Then we can combine with its failure link's min_len because patterns from failure also end at this position. So after BFS, we can update: node.min_len = min(node.min_len, failure_node.min_len). But must be done in topological order from root outwards: when processing a node, its failure node's min_len should already be final (since failure node is closer to root). So BFS from root ensures that.
Thus, after building automaton, each node holds the minimum length among all patterns that end at strings corresponding to that node (including those from failure chain). Then scanning S: starting at root, for each character c, transition (using failure links as needed, but we can store direct go links via building "next" for each character to avoid traversing failures each time). Actually standard Aho-Corasick for scanning: we maintain state, and for each character we follow goto if exists, else follow failure links until we find a child, but we can precompute "delta" transitions (like building automaton with full transitions). Since alphabet is only 26, we can compute go for each node for each character, which is efficient: O(26 * total nodes). total nodes is at most total length of patterns ≤ 1e5, so it's okay. Then scanning is O(|S|) time.
At each position i, after transitioning to state v, we get v.min_len (the shortest pattern length ending at this position). If v.min_len is not INF, then we have min_len_end[i] = v.min_len. Else, no pattern ends at i.
Then we compute greedy:
last = 0 # last index where we placed a '*', initially 0.
ans = 0
for i in 1..|S|:
if min_len_end[i] != INF:
start = i - min_len_end[i] + 1
if start > last:
ans += 1
last = i
That yields answer.
But is it always correct to only consider the shortest pattern ending at i? That gives the maximum start. But what if there are patterns ending at i but the shortest one is length L_min, start = i - L_min + 1. That's the maximum start. So our condition start > last indicates there exists an uncovered interval. However, we need to be careful: Could there be a scenario where there is an occurrence that ends at i but with a larger start (shorter pattern) that is covered, but there is also an occurrence with a smaller start (longer pattern) that is uncovered? That would mean that start_small > last? No, if the larger start (max) is covered (i.e., <= last), then all starts are ≤ max start ≤ last, so they are all covered. So if max start ≤ last, all intervals ending at i are covered. So indeed checking max start is sufficient. So our algorithm is correct.
Now we must confirm that our derivation of max start from min length is correct, and that the automaton's min_len (shortest pattern ending at this state) indeed gives the minimum length among all patterns that are suffixes of the current string. This is true because the automaton state corresponds to the longest suffix that is a prefix of some pattern. However, the state's failure chain includes all suffixes that are prefixes of patterns. The patterns that end at current position are exactly those that correspond to nodes in the failure chain (including the current node) that have a pattern ending. The shortest length among them would be the smallest pattern that is a suffix. This is precisely what we compute by propagating min_len along failure links.
One nuance: The state after reading character c may not directly correspond to a pattern that ends at that character? Actually, if a pattern ends at this position, the automaton state after reading that character should be a node that has a pattern ending (or reachable via failure). In Aho-Corasick, when we process each character, we follow transitions that account for failure, so the state we end up in is the node representing the longest suffix of the processed prefix that is also a prefix of some pattern. This state and its failure chain represent all pattern suffixes. So we are correct.
Thus algorithm steps:
-
Build Aho-Corasick automaton for the set of patterns.
- Node structure: children[26], fail, min_len (initialize to INF).
- Insert each pattern: traverse/create nodes, at the final node, set min_len = min(min_len, len(pattern)).
- After insertion, build fail links via BFS (queue). For root's direct children, fail = root. For others, compute fail from parent.
- During BFS, after setting fail for a node, we update node.min_len = min(node.min_len, fail.min_len). This propagates the minimum pattern length from failure chain.
- Additionally, to speed scanning, we may compute "go" transitions: For each node and each character, if child exists, go = child; else if node is root, go = root; else go = go[fail][c]. But we can compute on the fly using while loops if we prefer; but precomputing is fine.
-
Scan S:
state = root
For i from 0 to len(S)-1 (0-indexed) or 1-indexed:
c = S[i] as index (0-25)
state = go[state][c] (or follow while loop)
if state.min_len != INF:
min_len_end[i] = state.min_len
else:
min_len_end[i] = INF (or 0 sentinel)
-
Greedy:
last = -1 (or 0 with 1-index)
ans = 0
for i in range(len(S)):
if min_len_end[i] != INF:
start = i - min_len_end[i] + 1 # using 0-index? careful: we need consistent indexing.
We need to decide indexing.
Let's define positions as 0-indexed for array. Let S indices 0..L-1. Occurrence of pattern of length L_p ending at index i means it starts at i - L_p + 1. last_placed is the index of the last placed '*' (0-indexed). Initially last_placed = -1 (no placement). Condition: if start > last_placed, then we need to place at i, set last_placed = i.
Edge: what if start == last_placed? If start <= last_placed, the interval is covered because the '' at last_placed is within the interval? For an interval [l, r] to be covered by a point p, we need l <= p <= r. If p == l? That's okay, p is within. So if start <= last_placed <= i? Actually last_placed is the index where we placed ''. If last_placed is between start and i inclusive, it's covered. If last_placed == start, it's covered. So condition for uncovered is start > last_placed (since if start > last_placed, then last_placed < start, and since last_placed is earlier, the interval does not include last_placed because the interval starts after last_placed, and ends at i (which is >= start > last_placed), so last_placed is before the interval. However, what if last_placed is after i? It's never because we process in increasing i and last_placed is always ≤ current i? Actually we place at i, so last_placed can be i or less. So condition start > last_placed ensures uncovered. So we use >.
Thus algorithm:
last = -1
ans = 0
for i in range(L):
if min_len_end[i] != INF:
start = i - min_len_end[i] + 1
if start > last:
ans += 1
last = i
Return ans.
Let's test with examples.
Example1: S = "brainfuck" (0-indexed). L=9? Actually "brainfuck": indices 0..8. Pattern "fuck" length 4, ending at index? 'f' at 5? Actually let's index: 0:b,1:r,2:a,3:i,4:n,5:f,6:u,7:c,8:k. So pattern "fuck" occupies indices 5-8? That would be length 4, start 5? That's "fuck"? Actually "fuck": f u c k, so start=5, end=8. So min_len_end[8]=4. Then start=8-4+1=5. last=-1 initially. At i=0..7 no pattern. At i=8: start=5 > -1 => ans=1, last=8. correct.
Example2: S="aaa" (0:a,1:a,2:a). Pattern "a" length 1. So min_len_end[0]=1, [1]=1, [2]=1. Process:
i=0: start=0 > -1 => ans=1, last=0
i=1: start=1 > 0 => ans=2, last=1
i=2: start=2 >1 => ans=3, last=2. correct.
Example3: "hellshakeyano". Let's index 0..12? Actually length 13? h e l l s h a k e y a n o -> indices 0 to 12. Patterns:
- "hell": length 4, end at index 3? Let's check: h(0) e(1) l(2) l(3) => yes end=3.
- "shake": s(4) h(5) a(6) k(7) e(8) => length5, end=8.
- "key": k(7) e(8) y(9) => length3, end=9.
So min_len_end[3]=4, start=0; at i=3, start=0 > -1 => ans=1, last=3.
min_len_end[8]=5 (maybe also other? But also maybe "hell"? No. So start=4? Actually 8-5+1=4. Since last=3, start=4 >3 => ans=2, last=8.
min_len_end[9]=3, start=7, last=8 => start=7 <=8 => no action. So ans=2. Correct.
Thus algorithm works.
Now we must consider correctness with overlapping intervals that might be covered by a point placed at an earlier end. Our algorithm uses greedy based on max start at each end. Is it guaranteed to produce minimum? The greedy for interval stabbing is optimal when intervals are sorted by right endpoint. Our simulation is exactly that, because we process ends in increasing order and place a point at end i if there exists an interval ending at i with start > last_placed. This is equivalent to scanning intervals in order of right endpoint and placing at the rightmost point of the first uncovered interval.
But we need to ensure that the intervals considered are exactly all occurrences. However, we are using only the "max start" at each end. Does this capture all intervals? Suppose there are multiple intervals ending at the same end i. The greedy algorithm only cares about whether any of them is uncovered. If any is uncovered, we must place a point at i (or later) to cover it. Placing at i is optimal because it covers all intervals ending at i and possibly others. So using max start is sufficient.
Now let's consider scenario: There is an interval ending at i with start > last_placed, but there is also an interval ending at j > i with start also > last_placed, but maybe we could place a point at j to cover both? However, the greedy algorithm would place at i because it's the earliest uncovered end, and that yields optimal solution. So our algorithm is correct.
Now confirm that we indeed need to consider all occurrences, not just the ones that are "minimal" in some sense. Suppose there is a pattern "ab" and a pattern "b". For S = "ab", occurrences: "ab" (start 0, end1) and "b" (start1, end1). Both end at index1. max_start at end1 is max(start) = start of "b" = 1? Actually start of "b" =1 (0-indexed?), let's use 0-index: S: index0='a',1='b'. "ab" length2, start0, end1. "b" length1, start1, end1. So max_start = 1 (since start1 > start0). min_len = 1. So at i=1, start = 1 - 1 + 1 = 1. last initially -1. So start=1 > -1 => place at i=1. That's one ''. But could we place at i=0? If we place '' at index0, then "ab" is broken (since includes index0) but "b" (substring at index1 alone) still exists because it doesn't include index0. So we would need another '*' at index1 to break "b". So minimum is 1 (place at index1 breaks both because both intervals include index1). So greedy gives 1, correct.
Now consider overlapping intervals across different ends. It's fine.
Now we must ensure that computing min_len_end via Aho-Corasick correctly gives the minimum length among patterns that end at i. But is it possible that a pattern ends at i but its length is not the minimum among patterns ending at i, but the maximum start (i.e., smallest length) is not captured if we only propagate the minimum length? Actually we are taking the minimum length, which gives maximum start. So good.
But there is nuance: In Aho-Corasick, when we are at state v, the set of pattern lengths that end at this position is the union of lengths from patterns at v and patterns at nodes reachable via failure links from v. However, the minimum length among them might be from a node that is not the current state but a failure ancestor. By propagating min_len during BFS, we ensure that v.min_len is the minimum among all patterns in its failure chain. So v.min_len is indeed the minimum length among all patterns that are suffixes of the current prefix.
Thus scanning yields min_len_end[i] = state.min_len.
But careful: Some patterns might be longer than the current matched suffix but still end at i? In Aho-Corasick, any pattern that ends at position i must be a suffix of the current prefix S[0..i]. And the automaton state (the one representing the longest suffix that is a prefix) will, via its failure chain, include all shorter suffixes that are also prefixes of patterns. So yes, all pattern endings are covered.
Hence algorithm seems correct.
Now, we must also consider the possibility that multiple patterns end at i but the minimum length pattern might be very short, leading to a large start. But that's fine.
Now we need to consider that the operation is to replace a character with '', not to delete it. The condition is that no substring equals any p_k. If we place '' at position i, it breaks any substring that includes i. So intervals that contain i are covered. In our stabbing approach, we place points at positions. However, note that if we place '' at position i, the character becomes ''. Could this affect other intervals that start after i? No, they are unaffected unless they include i. The stabbing model is correct: each interval is a set of positions (the indices of characters forming that substring). By placing '' at a position within the interval, the substring will contain '', so it cannot equal the pattern (since pattern consists only of lowercase letters). So interval is "covered" if at least one of its positions is chosen.
But careful: What about the possibility that after placing '', a new occurrence could be created? No, because '' is not a lowercase letter, so any substring containing it cannot equal a pattern consisting only of lowercase letters. So no new occurrences appear.
Thus the hitting set problem is correct.
Now we need to confirm that the greedy algorithm for interval stabbing yields the minimum number of points. This is classic for intervals on a line; the problem is a special case of the "minimum vertex cover" in interval graphs, which can be solved by selecting right endpoints. This holds because intervals are contiguous and we are selecting points (positions) that must be integers. The greedy algorithm yields optimal solution.
Thus the answer is the number of points placed.
Implementation details:
- Build AC automaton:
- Nodes: list of dict/array for children. Since alphabet size 26, we can use array of size 26 with -1 initially.
- Node: next[26], fail, min_len (int, initialized to INF, say large number like 10**9).
- We'll have nodes as a list of dictionaries? Better to use list of arrays for speed. In Python, using list of length nodes where each node is a dict might be okay for 1e5 nodes and 26 children per node? But using dict per node might be slower; we can store children as list of ints of length 26, and for memory we can use list of lists; but total nodes ~1e5, 26 ints each is 2.6 million ints, each int 28 bytes? That would be ~70 MB, maybe high but maybe okay? But Python overhead for list of lists is high. Better to store children in arrays of length total_nodes * 26? Use a 2D list: ch = [[-1]26 for _ in range(max_nodes)] but max_nodes ~ total length sum + 1 (1e5+1). That's 1e5 * 26 = 2.6e6 entries, each entry an int (28 bytes) = 72 MB, plus overhead for list of lists, might be too high (~200 MB). Could be near memory limit (typical AtCoder limit 1024 MB? Actually AtCoder often 1024 MB for Python? Usually 1024 MB or 2GB. But Python with 2.6e6 ints may be okay? Actually int objects in Python are 28 bytes each, so 2.6e6 * 28 ≈ 72.8 MB. Plus list overhead: each inner list has overhead ~56 bytes plus references to ints? Actually each inner list stores references to Python int objects, not the ints themselves. But the ints are small and may be cached? Actually Python integers are objects; but when we store -1, it's a single immutable int object reused. So each entry is a reference (8 bytes). So memory for the 2D list: outer list of 100001 references to inner lists (each 8 bytes) = 0.8 MB; each inner list: overhead (maybe 56 bytes) + array of 26 pointers (268=208) = 264 bytes, times 100001 ≈ 26.4 MB. Plus the int objects themselves: only distinct int objects? Actually each entry is a reference to the integer -1 (which is a singleton) or to other ints? The ints for child indices are small numbers (0..100000). Those are Python ints, each stored as object. When we assign a child index, e.g., 5, that's a Python int. But many nodes will have many -1 values, which are singleton. The other values are node indices, which are numbers up to 1e5. Those ints are also likely to be created but repeated? Each time we store a child index, it's the same integer object? In Python, small integers are cached (-5 to 256), but node indices can be up to 1e5, not cached. So each distinct integer object might be created many times? Actually if we assign ch[node][c] = next_node, where next_node is an int, that stores a reference to the same integer object; the integer object is created once when the node index is assigned (as an int). So for each node we have at most 26 references to ints, some of which are -1 (singleton) and others are node indices (each is a Python int object, but those ints are used throughout; each node index is a distinct integer object (like 5, 10, etc). But there are at most total_nodes (1e5) such int objects. However, each reference in the child array points to one of these int objects. So the memory for the int objects themselves is about 28 bytes * 1e5 ≈ 2.8 MB. So total memory for child array: outer list + inner lists + references + int objects = maybe around 30-40 MB. That's acceptable.
But we also need fail and min_len arrays: each list of length total_nodes. That's small.
Alternatively, we can use dictionary for children to save memory, but that may be slower. Since total nodes ~1e5 and alphabet 26, array is fine.
However, building direct transitions (goto) for each node for each character using BFS can be done. But we might not need to precompute full transition table if we simulate with while loops during scanning; but we need efficient O(|S|) scanning. In Python, using while loops per character might be okay if we have failure links but average depth small. But worst-case might be O(|S| * pattern depth) if we often follow failure many times. However, typical Aho-Corasick implementation with precomputed transitions using BFS is safer.
We can compute go array after building failure links: For each node and each character c:
if node has child c: go[node][c] = child
else if node == root: go[node][c] = root
else: go[node][c] = go[fail[node]][c]
We can compute this recursively/dp style using BFS. We can also compute on the fly during scanning using dictionary and failure fallback; but precomputing 26 * nodes may be memory heavy but still okay. Since nodes <= 1e5+1, 2.6 million entries, each integer, as above, memory ~30-40 MB plus overhead for list-of-lists maybe up