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 OCaml (4.02.3) (judge verdict: Accepted)

open Printf open Scanf
open Array

let split2 s t =
  let ls,lt = String.(length s,length t) in
  if ls<lt then [s]
  else if ls=lt then (
    if s=t then ["";""] else [s]
  ) else (
    let res = Str.split (Str.regexp_string t) s in
    let res = if String.sub s 0 lt = t then ""::res else res in
    let res = if String.sub s (ls-lt) lt = t then
      List.rev @@ ""::List.rev res else res in
    res
  )

let count_substr s t =
  List.length (split2 s t) - 1

let () = scanf " %d" @@ fun n ->
  let arr = init n (fun _ -> scanf " %s" @@ fun s -> s)
  in
  let kba,kbx,kxa,kab = ref 0,ref 0,ref 0,ref 0 in
  iter (fun s ->
    let bx = s.[0] = 'B' in
    let xa = s.[String.length s-1] = 'A' in
    let ba = bx && xa in
    if ba then incr kba
    else if bx then incr kbx
    else if xa then incr kxa;
    kab := !kab + count_substr s "AB"
  ) arr;
  let kba,kbx,kxa,kab = !kba,!kbx,!kxa,!kab in
  print_int @@ kab +
    if kba >= 1 then (
      let pair_ba = kba - 1 in
      let add,kbx =
        if kbx > 0 then 1,kbx-1 else 0,kbx in
      let add,kxa =
        if kxa > 0 then add+1,kxa-1 else add,kxa in
      pair_ba + add + min kbx kxa
    ) else
      min kbx kxa