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)]
#![allow(unused_imports)]
use ascii::AsciiChar;
use ascii::AsciiStr;
use itertools::Itertools as _;
use permutohedron::LexicalPermutation as _;
use petgraph::algo::dijkstra;
use petgraph::algo::min_spanning_tree;
use petgraph::data::FromElements;
use petgraph::graph::NodeIndex;
use petgraph::graph::UnGraph;
use petgraph::unionfind::UnionFind;
use proconio::fastout;
use proconio::input;
use proconio::marker::Chars;
use proconio::marker::Usize1;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use superslice::Ext as _;

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

    // 元から文字列に入っているABをカウントしておく
    let mut ans: usize = 0;
    for vec in Ss.iter() {
        for i in 1..vec.len() {
            if vec[i - 1] == 'A' && vec[i] == 'B' {
                ans += 1;
            }
        }
    }

    let BAs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] == 'B' && s[s.len() - 1] == 'A')
        .collect();
    let BXs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] == 'B' && s[s.len() - 1] != 'A')
        .collect();
    let XAs: Vec<Vec<char>> = Ss
        .clone()
        .into_iter()
        .filter(|s| s[0] != 'B' && s[s.len() - 1] == 'A')
        .collect();
    // let others: Vec<Vec<char>> = Ss
    //     .clone()
    //     .into_iter()
    //     .filter(|s| s[0] != 'B' && s[s.len() - 1] != 'A')
    //     .collect();

    let mut XAs_rest = XAs.len();
    let mut BXs_rest = BXs.len();
    let BAs_rest = BAs.len();

    // まず、XAとBXの小さいほうに合わせて消費
    let smaller = min(XAs_rest, BXs_rest);
    ans += smaller;
    XAs_rest -= smaller;
    BXs_rest -= smaller;

    // まだ余っている場合
    let bigger_rest = max(XAs_rest, BXs_rest);
    if bigger_rest > 0 {
        ans += 1 + if BAs_rest >= 2 { BAs_rest - 1 } else { 0 };
    } else {
        ans += if BAs_rest >= 2 { BAs_rest - 1 } else { 0 };
    }

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