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::Read;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();

    let answer = solve(&buf);

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

fn solve(input: &str) -> String {
    let mut iterator = input.split_whitespace();

    let n: usize = iterator.next().unwrap().parse().unwrap();
    let mut s_ab: Vec<String> = Vec::new();
    let mut s_a: Vec<String> = Vec::new();
    let mut s_b: Vec<String> = Vec::new();
    let mut s_o: Vec<String> = Vec::new();
    for _ in 0..n {
        let s: String = iterator.next().unwrap().to_string();
        if s.starts_with('B') && s.ends_with('A') {
            s_ab.push(s);
        } else if s.ends_with('A') {
            s_a.push(s);
        } else if s.starts_with('B') {
            s_b.push(s);
        } else {
            s_o.push(s);
        }
    }

    let mut t: String = pop(&mut s_a, &mut s_ab, &mut s_b, &mut s_o);
    for _ in 0..(n - 1) {
        if t.ends_with('A') {
            t += &pop(&mut s_ab, &mut s_b, &mut s_a, &mut s_o);
        } else {
            t += &pop(&mut s_a, &mut s_ab, &mut s_b, &mut s_o);
        }
    }

    let mut count: usize = 0;
    for i in 0..(t.len() - 1) {
        if &t[i..i + 2] == "AB" {
            count += 1;
        }
    }
    return count.to_string();
}

fn pop(v1: &mut Vec<String>, v2: &mut Vec<String>, v3: &mut Vec<String>, v4: &mut Vec<String>) -> String {
    if !v1.is_empty() {
        return v1.pop().unwrap();
    }
    if !v2.is_empty() {
        return v2.pop().unwrap();
    }
    if !v3.is_empty() {
        return v3.pop().unwrap();
    }
    return v4.pop().unwrap();
}