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: Wrong Answer)

#![allow(non_snake_case)]

use std::io::{stdin, Read};
use std::str::FromStr;
fn read_option<T: FromStr>() -> Option<T> {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok()
}
fn read<T: FromStr>() -> T {
    let opt = read_option();
    opt.expect("failed to parse token")
}

fn main() {
    let N: usize = read();
    let mut ans = 0;
    let mut last_a = 0;
    let mut first_b = 0;
    let mut loop_flag = true;
    for _ in 0..N {
        let s: String = read();
        let first_str = &s[0..1];
        let last_str = &s[s.len() - 1..s.len()];

        if first_str == "B" {
            first_b += 1;
            if last_str != "A" {
                loop_flag = false;
            }
        }
        if last_str == "A" {
            last_a += 1;
            if first_str != "B" {
                loop_flag = false;
            }
        }

        for s2 in s.chars().collect::<Vec<char>>().windows(2) {
            if s2 == &(vec!['A', 'B'][..]) {
                ans += 1;
            }
        }
    }
    ans += std::cmp::min(last_a, first_b);
    ans += if loop_flag { -1 } else { 0 };
    println!("{}", ans)
}