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.42.0) (judge verdict: Wrong Answer)

#![allow(non_snake_case)]
use proconio::input;
// use std::collections::HashMap;

fn get_tuple(a: i32, b: i32) -> (i32, i32) {
    if a >= b {
        let bigger = a;
        let smaller = b;
        return (smaller, bigger);
    } else {
        let bigger = b;
        let smaller = a;
        return (smaller, bigger);
    }
}

fn main() {
    input! {
        N: usize,
        Ss: [String; N],
    }

    // 文字列を構築できれば勝ち...なのだが、
    // 実際に構築するとメモリを食いそうなので、
    // まず事前に文字列の中に含まれるABだけをカウントしておいて、
    // concatで発生するABのぶんを足すとよさそう。
    let mut ans: i32 = 0;

    for s in &Ss {
        ans += s.match_indices("AB").count() as i32;
    }

    // Bで始まる文字列
    // Aで終わる文字列
    // Aで終わる && Bで終わる文字列

    let starts_with_b = Ss.iter()
        .filter(|s| s.chars().nth(0) == Some('B'))
        .collect::<Vec<_>>()
        .len() as i32;
    let ends_with_a = Ss.iter()
        .filter(|s| s.chars().rev().nth(0) == Some('A'))
        .collect::<Vec<_>>()
        .len() as i32;
    let comm_b_a = Ss.iter()
        .filter(|s| {
            s.chars().nth(0) == Some('B') && s.chars().rev().nth(0) == Some('A')
        })
        .collect::<Vec<_>>()
        .len() as i32;

    // println!("{}", starts_with_b);
    // println!("{}", ends_with_a);
    // println!("{}", comm_b_a);

    let t = get_tuple(starts_with_b, ends_with_a);
    let smaller = t.0 - comm_b_a;
    let bigger = t.1 - comm_b_a;
    dbg!(ans);
    dbg!(smaller);
    dbg!(bigger);
    dbg!(comm_b_a);


    // smaller個は作れる
    ans += smaller;

    let bigger_rest = bigger - smaller;
    dbg!(bigger_rest);

    // bigger_restに1つつなぐと1つ増える
    if bigger_rest > 0 {
        ans += comm_b_a;
    }

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