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 print_list f ls = List.iter (fun v -> printf "%s " @@ f v) ls; print_newline ()

(* rosetta code *)
let count_substring str sub =
  let sub_len = String.length sub in
  let len_diff = (String.length str) - sub_len
  and reg = Str.regexp_string sub in
  let rec aux i n =
    if i > len_diff then n else
      try
        let pos = Str.search_forward reg str i in
        aux (pos + sub_len) (succ n)
      with Not_found -> n
  in
  aux 0 0

let () = scanf " %d" @@ fun n ->
  let arr = init n (fun _ -> scanf " %s" @@ fun s -> s)
  in
  let kba,kbx,kxa,krest = fold_left (fun (kba,kbx,kxa,krest) s ->
    let bx = s.[0] = 'B' in
    let xa = s.[String.length s-1] = 'A' in
    let ab = bx && xa in
    let kba = if ab then kba + 1 else kba in
    let kbx = if not ab then (
      if bx then kbx+1 else kbx
    ) else kbx in
    let kxa = if not ab then (
      if xa then kxa+1 else kxa
    ) else kxa in
    let krest = krest + count_substring s "AB"
    in
    (kba,kbx,kxa,krest)
  ) (0,0,0,0) arr in
  let hoge =
    if kba >= 1 then (
      let pair_ba = kba - 1 in
      let res = 0 in
      let res,kbx =
        if kbx > 0 then res+1,kbx-1 else res,kbx in
      let res,kxa =
        if kxa > 0 then res+1,kxa-1 else res,kxa in
      pair_ba + res + min kbx kxa
    ) else (
      min kbx kxa
    ) in
  print_int @@ krest + hoge