Problem:
Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4

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

use std::str::FromStr;
use std::fmt::Debug;
use std::cmp;

fn read_as_vec<T>() -> Vec<T>
where T: FromStr, <T as FromStr>::Err : Debug{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().map(|c| T::from_str(c).unwrap()).collect()

}

fn read_as_string() -> String{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}


fn main(){
    let n: usize = read_as_vec()[0];

    let mut ans: usize = 0;
    let (a, b) = (0, 0);
    let (mut both, mut beg, mut end) = (0, 0, 0);
    for _ in 0..n{
        let s = read_as_string();
        ans += s.matches("AB").count();
        let prefix = s.starts_with("B");
        let suffix = s.ends_with("A");
        if prefix && suffix{
            both += 1;
        }else if prefix{
            beg += 1;
        }else if suffix{
            end += 1;
        }
    }

    if both == 0{
        ans += cmp::min(beg, end);
    }else{
        ans += both-1;
        both = 0;
        if beg > 0{
            ans += 1;
            beg -= 1;
        }

        if end > 0{
            ans += 1;
            end -= 1;
        }

        ans += cmp::min(beg, end);
    }

    println!("{}", ans);
}