Problem:
Score : 400 points

Problem Statement

The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:

1 ≤ i < j < k ≤ |T| (|T| is the length of T.)

T_i = A (T_i is the i-th character of T from the beginning.)

T_j = B

T_k = C

For example, when T = ABCBC, there are three triples of integers (i, j, k) that satisfy the conditions: (1, 2, 3), (1, 2, 5), (1, 4, 5). Thus, the ABC number of T is 3.

You are given a string S. Each character of S is A, B, C or ?.

Let Q be the number of occurrences of ? in S. We can make 3^Q strings by replacing each occurrence of ? in S with A, B or C. Find the sum of the ABC numbers of all these strings.

This sum can be extremely large, so print the sum modulo 10^9 + 7.

Constraints

3 ≤ |S| ≤ 10^5

Each character of S is A, B, C or ?.

Input

Input is given from Standard Input in the following format:

S

Output

Print the sum of the ABC numbers of all the 3^Q strings, modulo 10^9 + 7.

Sample Input 1

A??C

Sample Output 1

8

In this case, Q = 2, and we can make 3^Q = 9 strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:

AAAC: 0

AABC: 2

AACC: 0

ABAC: 1

ABBC: 2

ABCC: 2

ACAC: 0

ACBC: 1

ACCC: 0

The sum of these is 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8, so we print 8 modulo 10^9 + 7, that is, 8.

Sample Input 2

ABCBC

Sample Output 2

3

When Q = 0, we print the ABC number of S itself, modulo 10^9 + 7. This string is the same as the one given as an example in the problem statement, and its ABC number is 3.

Sample Input 3

????C?????B??????A???????

Sample Output 3

979596887

In this case, the sum of the ABC numbers of all the 3^Q strings is 2291979612924, and we should print this number modulo 10^9 + 7, that is, 979596887.

Solution in Rust (1.15.1) (judge verdict: Accepted)

use std::ops::{Add, Mul, Rem};

const MOD: i64 = 1_000_000_007;

fn main() {
    let stdin = std::io::stdin();
    let mut locked = stdin.lock();
    let mut sc = scanner::Scanner::new(&mut locked);

    let s = sc.next_bytes();
    let mut dp = vec![vec![0i64; 4]; s.len() + 1];
    dp[0][0] = 1;
    for (i, &c) in s.iter().enumerate() {
        if c == b'A' {
            dp[i + 1][1] = dp[i + 1][1].add(dp[i][0]).rem(MOD);
            dp[i + 1][0] = dp[i + 1][0].add(dp[i][0]).rem(MOD);
            dp[i + 1][1] = dp[i + 1][1].add(dp[i][1]).rem(MOD);
            dp[i + 1][2] = dp[i + 1][2].add(dp[i][2]).rem(MOD);
            dp[i + 1][3] = dp[i + 1][3].add(dp[i][3]).rem(MOD);
        } else if c == b'B' {
            dp[i + 1][2] = dp[i + 1][2].add(dp[i][1]).rem(MOD);
            dp[i + 1][0] = dp[i + 1][0].add(dp[i][0]).rem(MOD);
            dp[i + 1][1] = dp[i + 1][1].add(dp[i][1]).rem(MOD);
            dp[i + 1][2] = dp[i + 1][2].add(dp[i][2]).rem(MOD);
            dp[i + 1][3] = dp[i + 1][3].add(dp[i][3]).rem(MOD);
        } else if c == b'C' {
            dp[i + 1][3] = dp[i + 1][3].add(dp[i][2]).rem(MOD);
            dp[i + 1][0] = dp[i + 1][0].add(dp[i][0]).rem(MOD);
            dp[i + 1][1] = dp[i + 1][1].add(dp[i][1]).rem(MOD);
            dp[i + 1][2] = dp[i + 1][2].add(dp[i][2]).rem(MOD);
            dp[i + 1][3] = dp[i + 1][3].add(dp[i][3]).rem(MOD);
        } else {
            dp[i + 1][1] = dp[i + 1][1].add(dp[i][0]).rem(MOD);
            dp[i + 1][2] = dp[i + 1][2].add(dp[i][1]).rem(MOD);
            dp[i + 1][3] = dp[i + 1][3].add(dp[i][2]).rem(MOD);
            dp[i + 1][0] = dp[i + 1][0].add(dp[i][0] * 3).rem(MOD);
            dp[i + 1][1] = dp[i + 1][1].add(dp[i][1] * 3).rem(MOD);
            dp[i + 1][2] = dp[i + 1][2].add(dp[i][2] * 3).rem(MOD);
            dp[i + 1][3] = dp[i + 1][3].add(dp[i][3] * 3).rem(MOD);
        }
    }
    println!("{}", dp[s.len()][3]);
}

mod scanner {
    use std::io::{BufRead, Error, ErrorKind, Read};
    use std::str::FromStr;

    pub struct Scanner<'a, R>
    where
        R: 'a + BufRead + ?Sized,
    {
        reader: &'a mut R,
    }

    impl<'a, R> Scanner<'a, R>
    where
        R: 'a + BufRead + ?Sized,
    {
        pub fn new(reader: &'a mut R) -> Self {
            Scanner { reader: reader }
        }

        #[allow(dead_code)]
        pub fn next_byte(&mut self) -> u8 {
            self.reader
                .bytes()
                .skip_while(|ref c| !Self::is_printable(*c.as_ref().ok().unwrap()))
                .next()
                .unwrap()
                .unwrap()
        }

        #[allow(dead_code)]
        pub fn next_bytes(&mut self) -> Vec<u8> {
            self.reader
                .bytes()
                .skip_while(|ref c| !Self::is_printable(*c.as_ref().ok().unwrap()))
                .take_while(|ref c| Self::is_printable(*c.as_ref().ok().unwrap()))
                .collect::<Result<Vec<u8>, _>>()
                .unwrap()
        }

        #[allow(dead_code)]
        pub fn next_unsigned(&mut self) -> u64 {
            self.reader
                .bytes()
                .skip_while(|ref c| !Self::is_printable(*c.as_ref().ok().unwrap()))
                .take_while(|ref c| Self::is_printable(*c.as_ref().ok().unwrap()))
                .fold(Ok(0), |s, x| {
                    s.and_then(|t| {
                        x.and_then(|y| {
                            if b'0' <= y && y <= b'9' {
                                Ok(t * 10 + (y - b'0') as u64)
                            } else {
                                Err(Error::new(ErrorKind::InvalidData, "found not a digit"))
                            }
                        })
                    })
                })
                .unwrap()
        }

        #[allow(dead_code)]
        pub fn next_signed(&mut self) -> i64 {
            self.reader
                .bytes()
                .skip_while(|ref c| !Self::is_printable(*c.as_ref().ok().unwrap()))
                .take_while(|ref c| Self::is_printable(*c.as_ref().ok().unwrap()))
                .fold(Ok([0i64, 0]), |s, x| {
                    x.and_then(|y| {
                        s.and_then(|t| {
                            if t[0] == 0 && y == b'-' {
                                Ok([-1, 0])
                            } else if b'0' <= y && y <= b'9' {
                                Ok([
                                    if t[0] == 0 { 1 } else { t[0] },
                                    t[1] * 10 + (y - b'0') as i64,
                                ])
                            } else {
                                Err(Error::new(ErrorKind::InvalidData, "found not a digit"))
                            }
                        })
                    })
                })
                .and_then(|s| Ok(s[0] * s[1]))
                .unwrap()
        }

        #[allow(dead_code)]
        pub fn next_float(&mut self) -> f64 {
            self.reader
                .bytes()
                .skip_while(|ref c| !Self::is_printable(*c.as_ref().ok().unwrap()))
                .take_while(|ref c| Self::is_printable(*c.as_ref().ok().unwrap()))
                .collect::<Result<Vec<u8>, Error>>()
                .and_then(|t| {
                    String::from_utf8(t).or(Err(Error::new(ErrorKind::InvalidData, "invalid data")))
                })
                .and_then(|s| {
                    f64::from_str(&s).or(Err(Error::new(ErrorKind::InvalidData, "invalid data")))
                })
                .unwrap()
        }

        fn is_printable(c: u8) -> bool {
            0x21 <= c && c <= 0x7e
        }
    }
}