CF BUDDY
← Problems·

1426F · Number of Subsequences

2000 · combinatorics, dp, strings

Problem: You are given a string ss consisting of lowercase Latin letters "a", "b" and "c" and question marks "?".

Let the number of question marks in the string ss be kk. Let's replace each question mark with one of the letters "a", "b" and "c". Here we can obtain all 3k3^{k} possible strings consisting only of letters "a", "b" and "c". For example, if s=s = "ac?b?c" then we can obtain the following strings: [["acabac", "acabbc", "acabcc", "acbbac", "acbbbc", "acbbcc", "accbac", "accbbc", "accbcc"]].

Your task is to count the total number of subsequences "abc" in all resulting strings. Since the answer can be very large, print it modulo 109+710^{9} + 7.

A subsequence of the string tt is such a sequence that can be derived from the string tt after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string "baacbc" contains two subsequences "abc" — a subsequence consisting of letters at positions (2,5,6)(2, 5, 6) and a subsequence consisting of letters at positions (3,5,6)(3, 5, 6).

Input Format: The first line of the input contains one integer nn (3n200000)(3 \le n \le 200\,000) — the length of ss.

The second line of the input contains the string ss of length nn consisting of lowercase Latin letters "a", "b" and "c" and question marks"?".

Output Format: Print the total number of subsequences "abc" in all strings you can obtain if you replace all question marks with letters "a", "b" and "c", modulo 109+710^{9} + 7.

Note: In the first example, we can obtain 99 strings:

  • "acabac" — there are 22 subsequences "abc",
  • "acabbc" — there are 44 subsequences "abc",
  • "acabcc" — there are 44 subsequences "abc",
  • "acbbac" — there are 22 subsequences "abc",
  • "acbbbc" — there are 33 subsequences "abc",
  • "acbbcc" — there are 44 subsequences "abc",
  • "accbac" — there is 11 subsequence "abc",
  • "accbbc" — there are 22 subsequences "abc",
  • "accbcc" — there are 22 subsequences "abc".

So, there are 2+4+4+2+3+4+1+2+2=242 + 4 + 4 + 2 + 3 + 4 + 1 + 2 + 2 = 24 subsequences "abc" in total.

Sample Cases

Case 1

Input

6
ac?b?c

Output

24

Case 2

Input

7
???????

Output

2835

Case 3

Input

9
cccbbbaaa

Output

0

Case 4

Input

5
a???c

Output

46

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback