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::fs::File;
use std::io::{stdout, BufWriter, Read, Write};
use std::thread;

fn main() {
    thread::Builder::new()
        .stack_size(32 * 1024 * 1024) // 32MB
        .spawn(run)
        .unwrap()
        .join()
        .unwrap();
}

/// ローカル環境なら _in.txt から入力を受ける
fn read_input() -> String {
    let stdin = std::io::stdin();
    let mut s = String::new();
    match option_env!("LOCAL") {
        Some(_) => File::open("src/_in.txt")
            .expect("File not found")
            .read_to_string(&mut s)
            .unwrap(),
        None => stdin.lock().read_to_string(&mut s).unwrap(),
    };
    s
}

fn run() {
    let out = stdout();
    let mut out = BufWriter::new(out.lock());
    let input = read_input();
    let mut input = input.split_whitespace();

    let in_n: i64 = input.next().unwrap().parse().unwrap();
    let in_s: Vec<String> = (0..in_n)
        .map(|_| input.next().unwrap().parse().unwrap())
        .collect();

    let mut count: i64 = in_s
        .iter()
        .map(|s| s.match_indices("AB").count() as i64)
        .sum();
    // B..A
    let mut ba = 0;
    // B..A以外
    let mut bz = 0;
    // B以外..A
    let mut za = 0;
    // B以外..A以外
    let mut zz = 0;
    for s in &in_s {
        if s.starts_with("B") {
            if s.ends_with("A") {
                ba += 1;
            } else {
                bz += 1;
            }
        } else if s.ends_with("A") {
            za += 1;
        } else {
            zz += 1;
        }
    }
    while za > 0 {
        za -= 1;
        while ba > 0 {
            ba -= 1;
            count += 1;
        }
        if bz > 0 {
            bz -= 1;
            count += 1;
        }
    }
    while zz > 0 {
        zz -= 1;
    }
    if ba > 0 {
        ba -= 1;
        while ba > 0 {
            ba -= 1;
            count += 1
        }
        if bz > 0 {
            bz -= 1;
            count += 1
        }
    }
    writeln!(out, "{}", count).ok();
}