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::io::*;
use std::str::FromStr;

fn main() {
    let n: usize = read();
    let mut s = Vec::new();

    let mut ans = 0;
    let mut fb = 0;
    let mut fbla = 0;
    let mut la = 0;
    for _ in 0..n {
        let si: Vec<char> = read::<String>().chars().collect();
        for i in 0..si.len()-1 {
            if si[i] == 'A' && si[i+1] == 'B' {
                ans += 1;
            }
        }
        if si[0] == 'B' {
            if si[si.len()-1] == 'A' {
                fbla += 1;
            } else {
                fb += 1;
            }
        } else if si[si.len()-1] == 'A' {
            la += 1;
        }
        s.push(si);
    }

    while fbla > 0 {
        if la > 0 {
            ans += 1;
            fbla -= 1;
        } else if fb > 0 {
            ans += 1;
            fbla -= 1;
        } else if fbla > 1 {
            ans += 1;
            fbla -= 1;
        } else {
            break;
        }
    }

    println!("{}", ans + std::cmp::min(fb, la));
}

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().unwrap()
}