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)

// This code is generated by [cargo-atcoder](https://github.com/tanakh/cargo-atcoder)
// Original source code:
/*
use proconio::{input, fastout};
use proconio::marker::Chars;
use std::cmp::min;
// use itertools::Itertools;

#[fastout]
fn main() {
  input!{
    n: usize,
    ss: [Chars; n]
  };
  let mut ab = 0;
  let mut a = 0;
  let mut b = 0;
  let mut ba = 0;
  for i in 0..n {
    let it1 = ss[i][0..ss[i].len()-1].iter();
    let it2 = ss[i][1..ss[i].len()].iter();
    for (s1, s2) in it1.zip(it2){
      if s1 == &'A' && s2 == &'B' {
        ab += 1;
      }
    }
    let f = ss[i][0];
    let l = ss[i][ss[i].len()-1];
    if f == 'B' && l == 'A' {
      ba += 1;
    } else {
      if f == 'B' {
        b += 1;
      }
      if l == 'A' {
        a += 1;
      }
    }
  }
  // dbg!(ab, a, b, ba);
  let mut ans = ab;
  if ba > 0 {
    ans += ba - 1;
    ba = 1;
  }
  if ba > 0 && a > 0 {
    ans += 1;
    a -= 1;
  }
  if ba > 0 && b > 0 {
    ans += 1;
    b -= 1;
  }
  ans += min(a,b);
  println!("{}", ans);
}
*/

fn main() {
    let exe = "/tmp/binB226DB7D";
    std::io::Write::write_all(&mut std::fs::File::create(exe).unwrap(), &decode(BIN)).unwrap();
    std::fs::set_permissions(exe, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
    std::process::exit(std::process::Command::new(exe).status().unwrap().code().unwrap())
}

fn decode(v: &str) -> Vec<u8> {
    let mut ret = vec![];
    let mut buf = 0;
    let mut tbl = vec![64; 256];
    for i in 0..64 { tbl[TBL[i] as usize] = i as u8; }
    for (i, c) in v.bytes().filter_map(|c| { let c = tbl[c as usize]; if c < 64 { Some(c) } else { None } }).enumerate() {
        match i % 4 {
            0 => buf = c << 2,
            1 => { ret.push(buf | c >> 4); buf = c << 4; }
            2 => { ret.push(buf | c >> 2); buf = c << 6; }
            3 => ret.push(buf | c),
            _ => unreachable!(),
        }
    }
    ret
}

const TBL: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BIN: &'static str = "<base64-encoded ELF executable removed>";