We need to count strictly increasing sequences p_1, p_2, ..., p_k of indices such that:
- Each s[p_i] = 'a'.
- For each i (1 ≤ i < k), there exists j with p_i < j < p_{i+1} and s[j] = 'b'.
Essentially we select some 'a' positions (at least one? The problem statement says sequences p1,...,pk; k could be 0? Probably k≥1? Typically sequences of any length, but if k=0 it's an empty sequence? The examples: For "abbaa", they list [1], [4], [5], [1,4], [1,5] => they didn't include empty sequence. Also they list sequences with k=1 and k=2. So k≥1. So count all non-empty strictly increasing sequences of 'a' positions satisfying that between consecutive chosen 'a' positions there is at least one 'b'. That's the condition.
We need to count all such sequences modulo 1e9+7.
Let n = |s| ≤ 1e5.
Observation: The condition only cares about positions of 'a' and 'b'. Other letters? The string consists of lowercase Latin letters, but condition only cares about 'a' and 'b'. However, other letters are treated as neither 'a' nor 'b', so they do not satisfy the requirement of being a chosen 'a' nor do they serve as a 'b' for the between condition. Therefore, they effectively break the chain: between two 'a's, we require at least one 'b', and that b cannot be any other letter. So other letters are irrelevant? Actually they matter: If there is a 'c' between two a's, but no 'b', then we cannot select those two a's consecutively in the sequence because condition requires existence of a 'b' between them. So the presence of other letters doesn't help; only 'b's count as the required separating letter.
Thus, we need to count all non-empty subsets (ordered increasing) of the positions of 'a' such that between any two consecutive selected a's, there is at least one 'b'. That is like we partition the set of a positions into groups separated by at least one b? Actually the condition is only about the consecutive chosen a's. So it's like we can pick any a positions, but the distance between any two chosen a's must have a b in between. If there are multiple a's with no b between them (i.e., consecutive a's or a's separated only by non-b characters), they cannot both be chosen unless we pick them with something else? Wait, condition: For i<k, there exists j such that p_i < j < p_{i+1} and s_j = 'b'. So if we pick two a's that have no b between them, we cannot have them as consecutive in the sequence. However, we could still include both if there is some intermediate a between them that is chosen, provided that between each consecutive pair there is a b. But if we have a block of consecutive a's (or a's separated by non-b) with no b, then we cannot have any two of them consecutively in the sequence because there is no b between them. But you could skip some a's? Suppose positions a1, a2, a3 all are a's and there is no b in between any of them. If we select a1 and a3, condition requires a b between a1 and a3. Since there is none, we cannot pick a1 and a3 consecutively. Could we pick a1, a2, a3? Between a1 and a2, no b -> invalid. So any sequence of length >1 of a's chosen from such a block is impossible. So from a block of a's with no b's between them, we can only select at most one a. That a can be selected alone, or possibly combined with a's from other parts if separated by b's. So essentially, we have to consider the string segmented by b's? Not exactly because b's can appear multiple times. But the condition only cares about existence of at least one b between chosen a's. This means that if we look at the positions of b's, they define intervals: between two b's? Let's think.
Alternatively, we can transform the problem: For each a position, we can decide to include it or not, and the chosen set must satisfy: For any two chosen a's, if there is no b between them, then there must be at least one other chosen a between them? No, the condition is only about consecutive chosen a's. If we have three chosen a's at positions p<q<r. The condition requires: between p and q, there is a b; between q and r, there is a b. It does not require a b between p and r. So the condition is local between successive picks.
Therefore, the valid sequences correspond to increasing sequences of a positions such that the interval (p_i, p_{i+1}) contains at least one b. This is like we can only jump from one a to another if there is at least one b between them.
Thus, if we consider the string, we can precompute for each a position the next a position that is "reachable" with a b in between? More systematically, we can count all such sequences via DP.
Let the indices where s[i] = 'a' be a_1 < a_2 < ... < a_m. Also let B be the set of indices where s[j] = 'b'. For each pair (a_i, a_j) with i<j, we need to know if there exists a b between them, i.e., there exists some index b in B such that a_i < b < a_j.
If we want to count all increasing sequences of these a indices where each consecutive pair satisfies that condition, we can define DP[i] = number of valid sequences that end at a_i (i.e., whose last element is a_i). The total number of non-empty sequences is sum of DP[i] over i. For DP[i], we need to sum over all previous a_j (j < i) such that there is at least one b between a_j and a_i, plus the possibility of sequence of length 1 (just a_i). So DP[i] = 1 + sum_{j < i, condition holds} DP[j]. Then answer = sum_i DP[i] mod M.
However, the condition "exists b in (a_j, a_i)" can be precomputed efficiently if we process i in increasing order. As we iterate through a positions, we can maintain cumulative sum of DP[j] for those j that have "the next b after a_j is before a_i"? Actually we need to know for each a_i, which earlier a_j have at least one b between them and a_i. This is equivalent to: The smallest b index greater than a_j must be less than a_i. Or, the largest b index less than a_i must be greater than a_j. Both perspectives.
Define for each a position, we can find the nearest b to the left? Let's think.
We have list of a positions: a[1..m]. We also have list of b positions: b[1..B]. For each a_i, we can find the index of the first b after a_i (call next_b[a_i]), and similarly the last b before a_i (prev_b[a_i]).
Now, for a pair (a_j, a_i) with j < i, there is a b between them iff next_b[a_j] < a_i (since there must be a b after a_j and before a_i). Or equivalently, if the next b after a_j exists and is less than a_i.
But note that if next_b[a_j] is not defined (no b after a_j), then no later a_i can have a b between, so j cannot be followed by any later a. That's fine.
Thus, when processing a_i, we want to sum DP[j] for all j < i such that next_b[a_j] < a_i.
We could maintain a data structure (e.g., Fenwick tree) over a sorted order based on next_b values. As we iterate i from 1 to m, we need to query sum of DP[j] for j < i whose next_b[a_j] < a_i. But careful: The condition j < i is automatically satisfied if we process in order? Actually if we process i in increasing order, j < i is automatically. But we also need next_b[a_j] < a_i. However, a_i is increasing as i increases, but next_b[a_j] is a fixed value for each j. So we could maintain a BIT indexed by something like the positions of a? But we need to filter by next_b[a_j] < current a_i.
Alternatively, we can sort the indices j by next_b[a_j] and then while processing a_i, we add all DP[j] whose next_b[a_j] < a_i into a running sum. But we also need to ensure we only consider j < i? Actually if we add DP[j] for all j with next_b[a_j] < a_i, we might include j > i? Since i is the current index in the sorted a list, and we are processing in order of a_i. For j > i, next_b[a_j] might be < a_i? Possibly, but since a_j > a_i for j > i, next_b[a_j] could be less than a_i? Example: a_j is later, but next_b after a_j could be before a_i? That seems impossible because next_b after a_j is some b > a_j, and a_j > a_i, so that b > a_j > a_i, so cannot be < a_i. So if j > i, then a_j > a_i, then any b after a_j is > a_j > a_i, so next_b[a_j] > a_i. So indeed, for j > i, next_b[a_j] > a_i. Thus the condition next_b[a_j] < a_i automatically implies a_j < a_i? Not exactly; could there be a_j < a_i but next_b[a_j] < a_i? Yes. Could there be a_j > a_i and next_b[a_j] < a_i? No because next_b[a_j] > a_j > a_i. So the condition next_b[a_j] < a_i is sufficient to guarantee j < i (since a_j < a_i). Conversely, if a_j < a_i but next_b[a_j] might be > a_i, then the condition fails. So we can simply sum DP[j] for all j with next_b[a_j] < a_i, regardless of their index relative to i, but due to ordering, they will be among earlier a's. So we can treat DP contributions based on next_b threshold.
Thus DP[i] = 1 + sum_{j: next_b[a_j] < a_i} DP[j].
But careful: This would include j = i? next_b[a_i] is the next b after a_i; is it possible that next_b[a_i] < a_i? No, next_b > a_i by definition. So j=i is not counted because condition fails.
Thus, we need to maintain a cumulative sum over all processed a_j (since we process in increasing order of a_i) of DP[j] where we have added them to some structure when their next_b becomes "available"? Actually we need to sum over all j such that next_b[a_j] < a_i. Since we process a_i in increasing order, as a_i increases, more j become eligible because the threshold a_i increases. But we have to add DP[j] to the sum as soon as we know that for future a_i, the condition next_b[a_j] < a_i will be satisfied when a_i exceeds next_b[a_j]. So we could sort all a_j by next_b[a_j] (or simply as we process a_i, we can also add DP[j] to a running sum when next_b[a_j] becomes less than the current a_i? But we need to know which j have already been added. Since we process a_i in order, we can also process j in order of next_b[a_j]. For each a_i, we need to include all j with next_b[a_j] < a_i. Since next_b values are themselves indices in the string, we can maintain a pointer that sweeps over a sorted list of next_b values of the a's we have encountered so far.
But we are processing a_i in order of index (increasing). As we go, we have computed DP[i] for each a_i. Then we can insert DP[i] into a Fenwick tree or just add to a cumulative sum, but we need to be able to query sum over those j whose next_b < some threshold. However, the DP[i] values we will need to query for later a_i. So we can maintain a Fenwick tree over next_b values (or compress them) to support adding DP[i] at position corresponding to next_b[a_i] and then query for sum of DP over all entries with next_b < a_i (the current a_i). That would work: For each a_i, we compute DP[i] = 1 + query(BIT, key = a_i - 1) where BIT stores DP values indexed by next_b value (the position of the next b after a_i). Then we add DP[i] to BIT at index next_b[a_i] (if next_b exists; if there is no next b after a_i, then it cannot contribute to any later a because condition would never be satisfied since no b after it; but could it still be used? For later a_j, we need next_b[a_i] < a_j. If next_b[a_i] does not exist, then condition fails for all later a_j. So we don't need to add it to BIT. However, careful: We also might have case where there is a next_b but it's at position > some later a_j? That's fine; we add it and when querying for a_j we only sum those with next_b < a_j. So if next_b[a_i] is large, it won't be included until a_j exceeds that value. So we should add DP[i] to BIT at index next_b[a_i] only if next_b[a_i] exists; else we skip (or add at a sentinel beyond n). But we need to ensure that we only sum contributions from j for which next_b exists and is less than a_i. So for j with no next_b, they never contribute to later sequences (since condition requires existence of b). So they should not be added to BIT.
But we must consider also that DP[i] itself may include contributions from earlier a_j that might not have next_b? Actually earlier a_j with no next_b would not have been added to BIT, so they wouldn't contribute to later sums, which is correct because any later a_i would need a b between them, but if a_j has no b after it, then there is no b between a_j and any later a_i, so a_j cannot be followed by later a_i. So DP[i] won't include those contributions. So the BIT approach seems correct.
Now we need to compute next_b for each index? Actually we need next_b for each a position. We can precompute next_b for all positions in the string: For each index i, the next occurrence of 'b' after i (including i+1). Since we only need for a positions, we can compute by scanning from right to left: maintain last_b = INF; for i from n down to 1, if s[i]=='b', set last_b = i; then next_b[i] = last_b if last_b != INF else "none". For each a position, we take its next_b. That's O(n).
Now, we need to sort a positions increasingly. Let's list all indices where s[i]=='a'. We'll have array A[0..m-1] (0-indexed). For each a, compute next = next_b[a] if exists else sentinel maybe n+1 or something.
We will process i from 0 to m-1. For each a_i, we need to query BIT for sum of DP of earlier a_j whose next_b < a_i. BIT is indexed by next_b value (position). We need to map each next_b (which is an integer from 1 to n) to an index in BIT. We can compress the values of next_b among all a positions (including maybe sentinel). Since we only query for threshold a_i (which is an index), we need to be able to query sum over all entries with next_b value < a_i. a_i itself is a position, and next_b values are positions. So we can use a BIT over the range [1..n] or we can compress all possible query thresholds? But a_i can be up to n, so we can just use BIT of size n, since n ≤ 1e5, that's fine. We'll allocate BIT of size n (or n+2). That's fine.
So BIT supports:
- add(pos, val): add val at index pos.
- sum(pos): sum of values at indices ≤ pos.
We want sum of DP[j] for next_b[j] < a_i, i.e., sum over positions ≤ a_i-1. So query = BIT.prefix_sum(a_i - 1). Then DP[i] = 1 + query mod M.
Then after computing DP[i], if next_b[a_i] exists (i.e., ≤ n), we add DP[i] to BIT at index next_b[a_i]. Else, we do nothing (since no later a can be preceded by this a). But is there a nuance? If next_b[a_i] exists but equals something? It must be > a_i. So we add at that position.
This seems straightforward. Let's test on examples.
Example 1: s = "abbaa". Indices: 1:a, 2:b, 3:b, 4:a, 5:a.
A = [1,4,5].
Compute next_b:
- For index 1: next b after 1? s[2]='b', so next_b[1]=2.
- Index 4: next b after 4? positions: 5 is 'a', no b after 4 (since string ends). So next_b[4]=none.
- Index 5: next b after 5 = none.
Process i=0, a=1. query BIT sum indices <1 => 0. DP[0]=1. next_b=2 exists, add DP=1 at pos 2. BIT: at 2:1.
i=1, a=4. query BIT sum <4 => sum indices 1..3. BIT has at 2:1, so sum=1. DP[1]=1+1=2. next_b=none, do not add to BIT.
i=2, a=5. query BIT sum <5 => sum indices 1..4. BIT still has at 2:1, so sum=1. DP[2]=1+1=2. next_b=none, skip.
Total sum DP = 1+2+2 = 5. matches example.
Example 2: s = "baaaa". indices:1:b,2:a,3:a,4:a,5:a. A = [2,3,4,5].
Compute next_b:
- For index 2: next b after 2? positions: 3,4,5 are a, no b, so none.
- index3: none.
- index4: none.
- index5: none.
Process:
i=0 a=2, query sum<2 =>0, DP=1, next_b=none skip.
i=1 a=3, query sum<3 =>0, DP=1.
i=2 a=4, query =>0, DP=1.
i=3 a=5, query=>0, DP=1.
Total=4. matches.
Example 3: s="agaa". indices:1:a,2:g,3:a,4:a. A=[1,3,4].
Compute next_b: There is no 'b' anywhere. So next_b for all a = none.
Thus all DP=1, total=3. matches.
Another test: s="aba". indices:1:a,2:b,3:a. A=[1,3].
next_b[1]=2 (since b at2). next_b[3]=none.
Process: i=0 a=1, query sum<1 =>0, DP=1, add at 2:1.
i=1 a=3, query sum<3 => sum indices 1..2 => BIT has at2:1 => sum=1. DP=1+1=2. total=3. Let's enumerate: sequences: [1], [3], [1,3] (since there is b between). So 3. Good.
Now test: s="ababa". indices:1:a,2:b,3:a,4:b,5:a. A=[1,3,5].
next_b[1]=2, next_b[3]=4, next_b[5]=none.
Process:
i=0 a=1, query0 =>DP1, add at2:1.
i=1 a=3, query sum<3 => sum indices1..2: at2:1 => sum=1 => DP=2, add at4:2.
i=2 a=5, query sum<5 => sum indices1..4: at2:1, at4:2 => sum=3 => DP=1+3=4. total=1+2+4=7.
Enumerate? Let's see: all nonempty sequences of a positions satisfying condition. Positions:1,3,5. Condition: between consecutive, must be a b. Between 1 and3: there is b at2, ok. Between3 and5: b at4, ok. So all subsets of {1,3,5} where order is increasing, and we must have at least one b between consecutive. Since there is b between 1-3 and 3-5, any increasing sequence (i.e., any subset) is valid because if we skip an a, say pick 1 and5, between them there are b's at2 and4, but condition only requires existence of at least one b between them, and indeed there is b at2 (and 4). So any pair works. So all nonempty subsets of 3 elements: total 2^3-1=7. matches.
Now test: s="aab". indices:1:a,2:a,3:b. A=[1,2].
next_b[1]=3? after index1, next b at3, so next_b[1]=3. next_b[2]=3 as well? after index2, next b at3, so next_b[2]=3.
Process:
i=0 a=1, query sum<1 =>0, DP=1, add at3:1.
i=1 a=2, query sum<2 => sum indices1..1 =>0 (since BIT has at3). So DP=1, add at3: now we add DP=1 at3? Actually next_b[2]=3, so we add DP=1 at index3 as well (cumulative at3 becomes 2). But note: when computing DP[1], we only summed over j with next_b < a_i=2. next_b[1]=3 which is not <2, so it didn't contribute. That's correct because between a1=1 and a2=2 there is no b (since b at3 >2). So [1,2] is invalid. So DP[2] =1. total=2. Enumerate: sequences: [1], [2] (and [1,2] invalid). So answer=2. Works.
Now test: s="abab". indices:1:a,2:b,3:a,4:b. A=[1,3].
next_b[1]=2, next_b[3]=4.
DP[0]=1 add at2.
DP[1] query sum<3 => sum indices1..2 => at2:1 => DP=2, add at4.
total=3. Enumerate: [1], [3], [1,3] valid. Good.
Now test: s="a b a a b"? Actually consider "a a b a". indices:1:a,2:a,3:b,4:a. A=[1,2,4].
next_b[1]=3, next_b[2]=3, next_b[4]=none.
Process:
i=0 a=1: DP1, add at3:1.
i=1 a=2: query sum<2 =>0 -> DP1, add at3: now BIT at3=2.
i=2 a=4: query sum<4 => sum indices1..3 => BIT has at3:2 => sum=2 -> DP=1+2=3. total=1+1+3=5.
Enumerate valid sequences:
All nonempty sequences of a positions: {1}, {2}, {4}, {1,2}, {1,4}, {2,4}, {1,2,4}. Check condition:
- {1,2}: between 1 and2, there is no b (b at3 >2) => invalid.
- {1,4}: between 1 and4, there is b at3 => valid.
- {2,4}: between 2 and4, there is b at3 => valid.
- {1,2,4}: consecutive pairs: 1-2 invalid because no b, so invalid.
So valid sequences: [1], [2], [4], [1,4], [2,4] => total 5. matches.
Our DP gave 5. Good.
Now consider string with multiple b's and a's: algorithm seems correct.
Complexities: O(n) to compute next_b, O(m log n) for BIT operations, m ≤ n.
But we must be careful about modulo.
Now, what about other letters? They are not b, so they don't satisfy the condition. As we computed next_b, we only consider b's. So that's fine.
Edge Cases:
- No 'a'? Then answer should be 0 (since no nonempty sequences). Our m=0, sum=0, output 0.
- Only 'a's and no 'b's: Then any sequence of a's of length >=2 is invalid because no b between consecutive a's. So only sequences of length 1 are valid. So answer = number of a's. Our algorithm: next_b for each a = none, so DP[i]=1 each, total=m, correct.
- Only 'b's: no a's, answer 0.
- Mixed: fine.
Thus solution: iterate through s, collect indices of 'a', compute next_b for each position using a reverse scan. Then BIT of size n (or n+2). Process each a in increasing order: query = bit.sum(a-1); DP = (1 + query) % MOD; ans = (ans + DP) % MOD; if next_b exists (i.e., <= n) then bit.add(next_b, DP). After processing all a, output ans.
But is there any subtlety: The BIT query sum(a-1) will include contributions from a_j whose next_b is < a_i, but also those a_j whose next_b is 0? next_b is at least 1. So fine.
One nuance: If there is a b exactly at the position a_i? No, because a_i is an a, so b can't be at same index. next_b is defined as first b after a_i, so next_b > a_i.
Now, we must ensure that for a_i, the query uses a_i - 1 (strictly less). Because condition requires next_b[a_j] < a_i (strict). That's correct.
But what about the case where next_b[a_j] equals a_i? That would mean there is a b at position a_i? But a_i is an a, so that's impossible. However, next_b could be exactly a_i if a_i itself is a b, but it's not. So fine.
Now, is there any scenario where we need to consider that the condition requires existence of a b between p_i and p_{i+1}. That b could be anywhere in between, not necessarily directly after p_i. Our approach using next_b ensures that if there is any b between a_j and a_i, then the smallest b after a_j is less than a_i, so condition satisfied. Conversely, if the smallest b after a_j is ≥ a_i, then there is no b between, because any b after a_j would be at or after a_i, thus not in the interval (a_j, a_i). So condition is equivalent.
Thus DP recurrence correct.
Now let's double-check: The recurrence DP[i] = 1 + sum_{j: next_b[a_j] < a_i} DP[j] counts all sequences ending at a_i. Indeed, any such sequence either has length 1 (just a_i) or ends with some previous a_j such that there is a b between a_j and a_i, and then any valid sequence ending at a_j can be extended. So sum includes all DP[j] for valid predecessors. This is typical counting of subsequences with constraint.
But wait: Could there be a sequence that ends at a_i and has length >1, and the second last is a_j, but there might be multiple b's? That doesn't matter.
Thus solution seems fine.
But careful: When we add DP[j] to BIT at index next_b[a_j], we are using next_b as the key for future queries. For a later a_i, we query all j with next_b < a_i. However, is it possible that for some j, next_b[a_j] is defined but > a_i? Then it wouldn't be counted, which is correct because condition fails. But also, what about j where next_b[a_j] is defined but the b is not the only one; but we just need existence. So the condition next_b[a_j] < a_i is necessary and sufficient.
Now, what about if there are multiple a positions with same next_b? That's fine; BIT accumulates.
Implementation details:
- n up to 1e5, BIT size n+2 (since indices 1..n).
- next_b array of size n+1, initialize with n+1 as sentinel indicating none. But for BIT add, we only add if next_b ≤ n. Use n+1 to represent none; then skip adding.
- Process positions from n down to 1: maintain next_b_pos = n+1. For i=n..1: if s[i]=='b', set next_b_pos = i; next_b[i] = next_b_pos.
But we need next_b for all positions i, but only for a positions. We could compute an array next_b_for_a while scanning the a positions from right? Alternatively compute next_b for all positions. Complexity O(n) which is fine.
Alternative: Without BIT, we could also maintain a cumulative sum as we iterate over a positions, but we need to filter by next_b. Perhaps we could sort a positions by next_b and use two pointers? Let's consider: As we process a_i in increasing order, we want sum of DP[j] for which next_b[a_j] < a_i. Since a_i is increasing, we could maintain a running sum total_sum of DP[j] for all j that have been "activated" when their next_b becomes less than current a_i. However, the activation condition depends on the current a_i: a j is activated when next_b[a_j] < a_i. Since a_i increases, once a_i surpasses next_b[a_j], j becomes activated and remains activated for all later a_i. So we could sort the a positions by their next_b, and as we iterate through a_i in increasing order, we also maintain a pointer that adds DP of earlier a_j to a sum when their next_b is less than the current a_i. But careful: The DP[j] we add must be those j that have been processed (i.e., a_j < a_i) because we are processing a_i in increasing order, so j < i automatically if we are adding DP[j] as we go. So we could do: while pointer < i and next_b[a_pointer] < a_i, add DP[pointer] to sum_active. But note that we need to add DP[pointer] to sum_active when next_b becomes less than current a_i. However, we process a_i in order of index. The next_b values may not be monotonic with respect to a_i. For instance, a_j earlier may have next_b very large, so it won't be added until later when a_i exceeds that next_b. That's okay. So we can maintain an array of a positions with their DP, and sort the indices by next_b. Then we can maintain a Fenwick tree? Actually simpler: maintain a variable active_sum that accumulates DP[j] for all j that have been processed and have next_b < current a_i. But we need to know when to add a particular j to active_sum. As we iterate i in increasing order of a_i, we could have for each j (processed) we need to add its DP to active_sum at the moment when current a_i exceeds next_b[a_j]. That suggests we need an event: when we pass next_b[a_j] (i.e., when a_i > next_b[a_j]), we add DP[j] to active_sum. Since a_i are increasing, we can sort events by next_b. However, the order of a_i is fixed (increasing indices). We can precompute the list of (next_b[a_j], j) for each a_j that has next_b, then sort these events by next_b. Then we can maintain a pointer over events: while events[ptr].next_b < a_i, add DP[events[ptr].j] to active_sum, and increment ptr. This would work without BIT, just a simple array and pointer, assuming we process a_i in order. Because we need to add DP[j] exactly once when a_i surpasses next_b. But careful: The condition is next_b[a_j] < a_i (strict). So when we reach a_i that is greater than next_b[a_j], we should include DP[j] in the sum for that and subsequent a_i. However, for a_i exactly equal to next_b? Not possible as argued, but if it were, then condition fails because need <; so we only add when a_i > next_b. So using pointer on sorted events by next_b works: For each a_i, we process all events with next_b < a_i (i.e., less than a_i) that haven't been added yet. That will give us the total sum of DP[j] for j where next_b[a_j] < a_i. Since j are all previous a's? Actually events include all a_j, not just those with j < i? But if we process a_i in order of increasing a_i (which corresponds to increasing index j as well, because a_j are sorted). However, the events list includes all a_j regardless of i. For an event j, we will process it when we encounter an a_i with a_i > next_b[a_j]. But what if j > i? That is, a_j > a_i. Then a_i < a_j, so next_b[a_j] might be less than a_i? Could that happen? Let's test: Suppose a_j > a_i, can next_b[a_j] be less than a_i? Since next_b[a_j] > a_j > a_i, so no. So any event with j > i will have next_b > a_j > a_i, so its next_b cannot be less than a_i. Therefore when we process a_i, only events with j < i will satisfy next_b < a_i. So events for j > i are not added yet because next_b is greater. But what about events for j < i that have next_b larger than a_i? They won't be added yet. So this works: We process a_i in increasing order; we maintain an index ptr over events sorted by next_b. We also need DP[j] available when we add event j. Since we process a_i in order, by the time we might add DP[j] for j < i, DP[j] has already been computed. So we can store DP for each a index.
Thus we can avoid BIT and use just a sum variable and sorting events. Complexity O(m log m) due to sorting events, but m ≤ n, O(n log n) fine. BIT also O(n log n). Both are okay. However, BIT uses extra O(n) memory but simpler to implement? Actually BIT is also simple, but the event approach might be slightly simpler as we don't need to worry about indices and fenwick. But we need to handle the case where next_b is none: those a_j never become active for any later a_i, so we don't include them in events. Also we need to compute DP[i] = 1 + active_sum (where active_sum is the sum of DP[j] for events that have been triggered so far). But is active_sum exactly sum over j with next_b < a_i? Yes, because we add DP[j] when we encounter next_b event and we never remove. And all events are from a_j with next_b defined. Also, note that active_sum includes DP[j] only if next_b < a_i. So DP[i] = 1 + active_sum.
But careful: When we process a_i, we need to ensure that active_sum includes all j such that next_b[a_j] < a_i. However, the events we add are triggered when next_b < a_i. But we process a_i in increasing order; we can process events before computing DP[i]. Specifically, before computing DP[i], we process all events (j, next_b) where next_b < a_i and which haven't been processed yet, adding DP[j] to active_sum. Then DP[i] = 1 + active_sum. After computing DP[i], we need to insert its event if next_b[a_i] exists; but the event will be processed later when we encounter a_i' > next_b.
Implementation steps:
- Collect list A of indices where s[i]=='a'.
- For each index a in A, compute next_b[a] (by scanning from right). If no b after, set next = INF (or None).
- Create an array events = [].
- For each a_idx in A (we'll keep order of A as we process), we will need mapping from the position in A to DP values. We'll have DP array of length m.
- For i from 0 to m-1:
- While event_pointer < len(events) and events[event_pointer].next_b < A[i]:
active_sum = (active_sum + DP[events[event_pointer].index]) % MOD
event_pointer += 1
- DP[i] = (1 + active_sum) % MOD
- total = (total + DP[i]) % MOD
- If next_b[A[i]] is defined (i.e., <= n), then create an event: (next_b, i). But we need to insert events in sorted order of next_b to process later. So we could pre-build an array of events for each i, then sort them by next_b. Then while processing A[i] in increasing order, we will also move event_pointer as described.
But careful: The events are sorted by next_b. When we process A[i] in increasing order, we need to ensure that events for indices with lower i might have larger next_b? That's fine because sorting by next_b independent of i. The while loop will process all events whose next_b < A[i], regardless of the original order. Since the events are sorted by next_b, as A[i] increases, we will gradually add more DP contributions.
But there is a subtlety: The events list includes events for all i, including those not yet processed (i.e., future a's). However, when we process an event for index j, we need DP[j] to be already computed. Since we are processing a_i in increasing order (by index value, which is also by A[i]), and we are adding events only for indices j when we have computed DP[j]. But if we pre-build events for all i, they may include indices j that are larger than current i. In the while loop, we might accidentally add an event for a future a_j if its next_b < current A[i] and its index j > i? But as argued, if j > i then A[j] > A[i]. Could next_b[A[j]] be < A[i]? That would require next_b[A[j]] < A[i] < A[j], which is impossible because next_b[A[j]] > A[j] (since next_b after A[j] is > A[j]). So next_b[A[j]] > A[j] > A[i], so it cannot be < A[i]. Therefore any event with next_b < A[i] must correspond to an index j with A[j] < A[i]? Not necessarily: next_b could be less than A[i] even if A[j] > A[i]? That would require a b after A[j] that lies before A[i] which is impossible because b after A[j] is > A[j] > A[i]? Wait, think: For a given index pos (A[j]), next_b is the smallest index > pos where s[index]=='b'. So next_b > pos always. If pos > A[i], then next_b > pos > A[i]. So next_b cannot be < A[i]. So indeed, events with next_b < A[i] must correspond to a_j such that a_j < A[i] (since next_b > a_j, and next_b < A[i] implies a_j < next_b < A[i]). So j < i because the a positions are sorted. Therefore, any event with next_b < A[i] will correspond to an a index that has already been processed (since we process in order). So it's safe to pre-build events for all i and sort them; when processing the while loop, we will only add those events for which DP is already known because their indices are < i. The event structure includes the index i. So we can safely add DP[event.i] because we've computed DP for that i earlier. However, we need to guarantee that when we add an event, its DP value is already computed. Since we compute DP in order of i (0..m-1), and events are sorted by next_b, it's possible that an event for some j < i has not been added to the list yet? Actually we pre-built the list of all events (all i that have next_b) and sorted by next_b. That's static. Then while processing a_i, we move event_pointer through this sorted list, adding DP[event.i] to active_sum. But note that when event_pointer points to an event with index j, we need DP[j] already computed. However, if events are sorted by next_b, it's possible that an event with j < i hasn't been encountered yet because its next_b is larger and hasn't been added yet, but that's fine. The issue is: Could there be an event with j > i (i.e., not yet processed) that has next_b < A[i]? As argued, no. So all events with next_b < A[i] correspond to indices j < i. Therefore DP[j] is computed. Good.
Thus we can implement this event approach without BIT. However, we must be careful with equalities: Condition requires next_b < a_i strictly. So in while loop we check events[ptr].next_b < A[i]. Good.
Edge Cases: If multiple a have the same next_b, they will be added at the same time when A[i] surpasses that next_b. However, what if some a's next_b is exactly equal to some later a_i? Since a_i is a position of a, and next_b is a b position, they cannot be equal because b and a are different letters. So not an issue.
Thus we can implement:
-
Read s, n = len(s)
-
Create list A = [i for i,ch in enumerate(s) if ch == 'a'] (1-indexed? We'll use 0-indexed indices but easier with 1-index for next_b. Let's keep 1-indexed for simplicity: positions from 1 to n. We can store indices as ints.
-
Compute next_b array for all positions: initialize next_b array of length n+2 with INF (n+1 maybe). last = n+1 (or a sentinel > n). For i from n down to 1: if s[i] == 'b', last = i; next_b[i] = last. If last remains n+1, then no b after i.
But careful: The next_b after i should be the first index > i where s[index]=='b'. So if we set last initially = n+1 (or INF) meaning none, then for i from n down to 1: if s[i]=='b', set last = i; then set next_b[i] = last. But this sets next_b[i] = i if s[i]=='b', which for a positions we don't care. But for a positions we need next b after i, not including i. So the algorithm as described: from right to left, keep track of the last seen b (the nearest b to the right). For position i, if we set next_b[i] = last (the closest b to the right including maybe i itself). For a positions i, s[i]!='b', so last after updating from i+1? Actually we should update after checking s[i]? Standard: start with last = INF. For i from n down to 1: if s[i]=='b', then last = i; next_b[i] = last. This would set next_b[i] to i if s[i]=='b', else to the last b seen so far (which is > i). That's correct because for a positions, next_b[i] will be the index of the first b to the right (since we haven't yet updated at i because it's not b). So that's fine.
But if there is no b to the right, last remains INF. For a positions, we need to treat as none. So we can set INF = n+1 (or any > n) and skip adding events.
Now, we have A list (positions). For each a in A, get nxt = next_b[a] if next_b[a] <= n else None.
-
m = len(A). If m==0: print 0 and exit.
-
Create list events = [] (each as tuple (nxt, idx)) for idx in range(m) where nxt <= n.
-
Sort events by nxt.
-
Initialize event_ptr = 0, active_sum = 0, total = 0.
-
We also need DP array of size m.
-
Iterate i from 0 to m-1:
a = A[i]
while event_ptr < len(events) and events[event_ptr][0] < a:
_, idx = events[event_ptr]
active_sum = (active_sum + DP[idx]) % MOD
event_ptr += 1
DP[i] = (1 + active_sum) % MOD
total = (total + DP[i]) % MOD
No need to add event now, as they are pre-added. But careful: The event for current i, if exists, should be already in events list. However, its next_b might be < a? But that can't happen because next_b > a (since next_b is > a). So it will not be processed in the while loop for this i because its nxt is > a. So it's fine to have it pre-added. But we must ensure that when we later process the while loop for a later a, we will add DP[i] at that time. Since events is sorted and includes all indices with next_b defined, it's okay.
But we need DP[i] to be known when we later process the event. Since we compute DP[i] now, and the event for i is in the events list, when we later reach a point where the while condition triggers (next_b < a_current), we will add DP[i] from the events list. That's fine as long as the DP[i] is stored.
Potential issue: The events list includes events for indices that we haven't computed DP for? For events with index j, they are pre-existing. When we later process an a_i, the while loop adds events in order of next_b. If an event corresponds to index j, we need DP[j] to be already computed. Since events are sorted by next_b, and we process a_i in increasing order, it's possible that we encounter an event for some j where j > i? As argued, if next_b of j is < a_i, then j < i. So DP[j] is computed. But wait, consider the scenario: Suppose we have two a's: a1=5, a2=10. next_b for a1=7, for a2=12. When we process i=0 (a=5), while loop: events sorted by next_b: first event (7,0). Since 7 < 5? No, 7 is not <5, so no addition. DP[0]=1+0=1. Then i=1 (a=10). While loop: check event (7,0) - 7 <10, so add DP[0]=1 to active_sum. event_ptr moves to next event (12,1), 12<10? false. So DP[1]=1+1=2. That's correct. The event for index1 (next_b=12) is not processed yet because its next_b is not less than a_i until later if there is an a_i >12, but there isn't. So fine.
Now, what about if there are multiple a's with same a? Not possible.
Now, does the while loop add events for indices that are not yet processed? In the above, at i=0, event_ptr=0, event (7,0) is for i=0. Its DP[0] is not yet computed at the moment before DP[0] is computed? But we process while loop before computing DP[i]. At i=0, before DP[0] is computed, active_sum =0, events[0].next_b=7, a=5, condition 7<5 false, so we don't add. Then we compute DP[0]. So DP[0] is known. Then later at i=1, before DP[1], while loop adds event (7,0) using DP[0] which is known. So that's fine.
Now, if there were an event with next_b < a_i for some i and index j < i, but the event hasn't been processed yet because event_ptr wasn't advanced earlier? That's exactly the case: at i, we will process all events with next_b < a_i, including those from earlier indices. So it's fine.
But what about the ordering of events: They are sorted by next_b. At i, we process all events with next_b < a_i. Since a_i is increasing, we will eventually process each event exactly once when a_i surpasses its next_b. However, what about the case where two events have the same next_b? If next_b equals some a_i? As argued, can't be equal because a_i is a, next_b is b. But in principle if they are equal, condition requires strictly less, so we should add them only when a_i > next_b? Actually condition is next_b < a_i. So if next_b == a_i, it's not satisfied. So if next_b equals a_i (shouldn't happen), we shouldn't add yet. Since we use <, we correctly wait until a_i > next_b. But if next_b equals a_i, it wouldn't be added at that i, but later if a_i increases beyond that value (but a_i's are positions of a, so they can't be equal to a b position). So safe.
Thus event approach works.
Now, we also need to consider: What about a_i that have next_b defined but the next_b might be less than a_i? That's impossible because next_b > a_i by definition (first b after a_i). So all next_b > a_i. So for the current a_i, its own event won't be processed in the while loop at this i because next_b > a_i.
Thus implementation is straightforward.
But wait: We need to include DP[i] in the total sum. However, we also need to include sequences that are of length 1. DP[i] includes that.
Now answer is total sum modulo MOD.
Now, is there any double counting? DP counts sequences ending at each a_i. Sum over i gives total number of nonempty sequences.
Now confirm with a more complex test: string with b's and a's and other letters: s = "acbda". indices:1:a,2:c,3:b,4:d,5:a. A=[1,5]. next_b[1]: after index1, next b at 3, so next_b=3. next_b[5]=none. Process: i=0 a=1, while events: event list includes (3,0). a=1, 3<1? false, DP=1. total=1. i=1 a=5, while: event (3,0): 3<5 true -> add DP0=1 to active_sum, DP=1+1=2, total=3. So answer=3. Enumerate: sequences: [1], [5], [1,5] (since b at 3 between). correct.
Now consider other letters that might be b? Only 'b' counts as b.
Now test string with multiple a's and b's but also other letters: "a x b a y a". indices:1:a,2:x,3:b,4:a,5:y,6:a. A=[1,4,6]. next_b[1]=3, next_b[4]=? after 4, next b? none, since only b at 3. So none. next_b[6]=none. Process: DP[0]=1; add event (3,0). DP[1]: a=4, while: event (3,0) 3<4 true -> active_sum=1, DP=2; total=1+2=3. DP[2]: a=6, while: no more events (next event maybe none), active_sum remains 1? Actually after processing event (3,0), event_ptr=1, no more events. So active_sum=1, DP=1+1=2; total=5. Enumerate: sequences of a positions: [1], [4], [6], [1,4] (b between), [1,6] (b between? between 1 and6, there is b at3, yes), [4,6]? between 4 and6, there is no b (5 is y, 3 is before 4), so invalid. So total 5. matches.
Now test: "b a b a a b a". indices:1:b,2:a,3:b,4:a,5:a,6:b,7:a. A=[2,4,5,7]. Compute next_b:
- For a2 (index2): next b after 2? index3=b, so next=3.
- a4: after 4, next b at6, next=6.
- a5: after5, next b at6, next=6.
- a7: after7, none.
Process:
Events: (3,0), (6,1), (6,2). sorted by next: (3,0), (6,1), (6,2).
i=0 a=2: while events[0] (3<2?) false -> DP0=1; total=1.
i=1 a=4: while: event (3,0) 3<4 -> add DP0=1 to active_sum=1; event_ptr=1; next event (6,1) 6<4? false; DP1 = 1+1=2; total=3.
i=2 a=5: while: still event_ptr=1, (6,1) 6<5? false; DP2 = 1+active_sum(1)=2? Wait active_sum currently=1? After i=1, active_sum=1. So DP2 = 1+1=2; total=5.
i=3 a=7: while: now process events with next_b<7: event_ptr=1 (6,1) 6<7 -> add DP1=2 -> active_sum=3; event_ptr=2 (6,2) 6<7 -> add DP2=2 -> active_sum=5; event_ptr=3; then DP3 = 1+5=6; total=5+6=11.
Now enumerate to verify? Let's try to count manually. Positions of a: 2,4,5,7. Condition: between consecutive selected a's must be at least one b.
We can list all nonempty valid sequences.
We can compute using DP formula: DP[i] = 1 + sum_{j: next_b[a_j] < a_i} DP[j]. Let's compute manually:
- For a2: DP=1 (only [2])
- For a4: eligible j: only a2 because next_b[a2]=3 <4, so DP=1+1=2 -> sequences ending at 4: [4] and [2,4]
- For a5: eligible j: a2 (next_b=3<5) and a4? next_b[a4]=6 which is not <5, so no. So sum DP_j =1, DP=1+1=2 -> sequences ending at5: [5] and [2,5] (since [4,5] invalid because no b between 4 and5)
- For a7: eligible j: a2 (3<7), a4 (6<7), a5 (6<7) => sum DP_j =1+2+2=5, DP=1+5=6 -> sequences ending at7: [7]; [2,7]; [4,7]; [5,7]; [2,4,7]; [2,5,7]; also? Wait DP sum gives total sequences ending at 7: 6 sequences. Let's list them:
Length1: [7]
Length2: [2,7] (valid: b at3), [4,7] (b at6), [5,7] (b at6) -> 3 sequences
Length3: [2,4,7] (2->4 has b at3, 4->7 has b at6) valid; [2,5,7] (2->5 has b at3? b at3 is between 2 and5, yes; 5->7 has b at6) valid; [4,5,7]? 4->5 no b -> invalid; [2,4,5,7] length4? but that includes 4->5 invalid. So only 2 length3 sequences.
That totals 1+3+2=6. Good.
Total sequences = 1+2+2+6=11. matches.
So algorithm works.
Now consider scenario with large number of a's, b's, and other letters: fine.
Now, we must be careful about modulo operations: MOD = 10^9+7.
Now, the BIT approach would also be fine. The event approach avoids BIT and is O(m log m) due to sorting events. Since m up to 1e5, that's fine.
But we need to ensure that the while loop condition uses < a_i strictly. Also ensure that we handle indices as 1-indexed to avoid confusion.
Implementation details:
- Input string s (could have newline). length up to 100k.
- Use 1-indexing: we can store positions as 0-indexed but then next_b indices also 0-indexed. Either is fine, as long as consistent.
Let's implement with 0-indexed positions: indices from 0 to n-1. Then a positions list A stores indices (0-based). next_b array of length n, where next_b[i] = the smallest index j > i with s[j]=='b', or a sentinel like n (or -1). For BIT we need indices 0..n-1, but easier to use 1-indexed BIT by adding 1. However with event approach, we can still use 0-indexed.
If using event approach, we need to sort events by next_b (0-indexed). For while condition: events[ptr].next_b < a_i. That's fine. Also note that next_b for a is always > a, so it's fine.
We need to compute next_b efficiently: iterate from n-1 down to 0, maintain next_b_pos = n (or some sentinel > n-1). If s[i]=='b', set next_b_pos = i. Then next_b[i] = next_b_pos. If next_b_pos == n, that means no b after i.
Thus for each a, if next_b[a] < n, then it's valid; else no event.
Now, the events list: for each i from 0 to m-1, if next_b[A[i]] < n, append (next_b[A[i]], i). Then sort events by next_b.
Processing:
active_sum = 0
event_ptr = 0
total = 0
DP = [0]*m
for i in range(m):
a = A[i]
while event_ptr < len(events) and events[event_ptr][0] < a:
idx = events[event_ptr][1]
active_sum = (active_sum + DP[idx]) % MOD
event_ptr += 1
DP[i] = (1 + active_sum) % MOD
total = (total + DP[i]) % MOD
Print total.
But is there any case where we need to include sequences of length > 0 only? We are summing DP which includes length 1, that's correct.
Now, one more nuance: The problem says "strictly increasing sequences p_1, p_2, …, p_k". Usually k can be 0? The examples include only non-empty sequences. So we assume k≥1. So total includes all non-empty sequences. So our answer is sum DP.
Now test edge: s with no a: total=0.
Now test: s with a and b but multiple b's: fine.
Now, does the algorithm handle large input? O(n) time for scanning plus O(m log m) for sorting events, m ≤ n, fine.
Potential pitfalls: The events list might contain many entries (up to m). Sorting them is okay. The while loop processes each event at most once, O(m). So overall O(m log m).
Now, we should double-check correctness in all cases, especially regarding the condition "there is such j that p_i < j < p_{i+1} and s_j = 'b'". This requires at least one b strictly between them. Our condition next_b[a_j] < a_i ensures there is at least one b after a_j before a_i. That's equivalent. But what if there is a b before a_i but after a_j, but also there might be other characters, it's fine.
Now consider a scenario: a_j has a b after it, but the next b is at position exactly a_i? That can't happen because a_i is an a, not b. So next_b[a_j] cannot equal a_i. So safe.
Now, what about the possibility that there is a b between a_j and a_i, but the next_b[a_j] is after a_i? That's impossible because next_b[a_j] is the first b after a_j. If there is any b between a_j and a_i, then the first such b would be < a_i. So condition is exactly next_b[a_j] < a_i. So equivalence holds.
Thus algorithm is correct.
Now, we need to ensure that we treat the DP sum as modulo.
Now, confirm that the event approach does not miss contributions from a_j that have next_b defined but next_b < a_i but whose DP was not added yet because event pointer hasn't reached them? The while loop processes all events with next_b < a_i in order of next_b. Since events are sorted by next_b, and we advance pointer as we go, we will eventually process each event when a_i exceeds its next_b. But we need to guarantee that for each a_i, all events with next_b < a_i have been processed. Since a_i are increasing, and events sorted by next_b, the while loop condition will process all events whose next_b < current a_i, because if an event has next_b < a_i, then its next_b is less than a_i, and since we haven't processed it yet, it must be that its next_b is >= previous a_{i-1}? Actually the pointer moves only forward, and we process events whenever next_b < a_i. Since a_i is increasing, once we pass a certain next_b threshold, we add that event, and all events with same or smaller next_b (since sorted) will have been processed. So at each step, active_sum includes DP for all j with next_b < a_i. Good.
Now, what about a_j where next_b is undefined? They never appear in events, and correctly never contribute.
Thus algorithm yields correct total.
Now we must also consider that sequences can be of any length k >= 1. The DP recurrence counts all sequences ending at a_i. Summing gives total.
Now, can we do even simpler? Possibly we can compute answer using combinatorics: For each segment of a's separated by b's? Actually consider the positions of b's partition the string into segments: between b's, we have sequences of a's possibly with other letters. But condition requires at least one b between consecutive chosen a's. So effectively, we can think of grouping a positions into blocks where within each block, there is no b between any two a positions? Actually define segments: The string can be divided at each b? But other letters also break? Let's think: The condition is about existence of b between a's. So if we have two a's with at least one b between them, they can be selected consecutively. But if there are multiple b's, it's still okay. So the constraint is that we cannot select two a's that are in the same "region" where there is no b between them. More precisely, define the set of a positions. For any two a positions, if there is no b between them, they cannot be consecutive in the sequence. However, they could be in the same sequence if there is an intermediate a that provides a b between? But that intermediate a itself must have a b between it and the next. So effectively, we cannot have two consecutive selected a's from the same "maximal consecutive group of a's with no b between them"? But note that there could be other letters that are not b between a's; those also don't count as b. So these groups are defined by the condition: there is no b between any two a's in the group? Actually, if there is any non-b character between them, that still doesn't count as b. So a group of a's that are separated by characters that are not b (could be a, c, d, etc.) but without any b in between are considered as having no b between any two a's within that group. Therefore, from each such maximal contiguous (in terms of the linear order) set of positions that contains no b, we can select at most one a? But careful: If there are a's with other letters in between, but still no b, then there is no b between them, so they cannot be consecutive. Could we select two a's from such a group with an intermediate a that is also selected? That would require that between the first and second a there is a b? No, because they are within the same b-less region, there is no b between any two positions. So if we select three a's from the same region: positions p<q<r. Between p and q there is no b, so they cannot be consecutive. So you cannot have q directly after p. But could you have p, then skip q, then r? That would be p and r consecutive in the sequence (since we skip q), and between p and r there is still no b (since the region has no b). So also invalid. Therefore, at most one a can be chosen from any maximal contiguous segment of the string that contains no b? Not exactly "contiguous segment of string", because there could be other letters that are not b between a's, but still no b. So if we define a "b-separated region" as intervals between b's? Actually, consider splitting the string at each b position. Removing b's gives segments that contain no b. But these segments might contain a's and other letters. Within a segment, there is no b, so any two positions in that segment have no b between them. Hence, we can select at most one a from each segment. However, is it possible to select a's from different segments? Yes, because between segments there is at least one b (the b that separates them). So the condition between a's from different segments is satisfied (since there is at least that b). So the problem reduces to: Partition the string into segments by b's (i.e., consider the substrings between b's). In each segment, you may choose 0 or 1 a from that segment. The sequences are formed by choosing a non-empty set of segments (in increasing order) and for each chosen segment, picking exactly one a position within that segment. The total number of such sequences = product over segments of (number of a's in segment + 1) minus 1? Actually, for each segment, you have the option to either skip it or pick exactly one a from it (since picking more than one a from the same segment would violate condition because there is no b between them). And if you pick a's from multiple segments, the order is increasing automatically. And the condition that between consecutive selected a's there is at least one b is automatically satisfied because there is at least one b between the segments