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: Wrong Answer)

(* O(|s|) *)
let string_count s sub =
  let n = String.length s in
  let sub_len = String.length sub in
  let reg = Str.regexp sub in
  let rec loop acc i =
    try
      if i >= n then
        acc
      else
        let j = Str.search_forward reg s i + sub_len in
        loop (acc + 1) j
    with
    | _ -> acc
  in
    loop 0 0

(* O(n^2) *)
let solve n ss =
  let b_start, a_end, both, ab = List.fold_left
    (fun (b_start, a_end, both, ab) s ->
      let count = string_count s "AB" in
      let new_ab = ab + count in
      let starts_b = s.[0] = 'B' and ends_a = s.[String.length s - 1] = 'A' in
      let new_b_start = if starts_b then b_start + 1 else b_start in
      let new_a_end = if ends_a then a_end + 1 else a_end in
      if starts_b && ends_a then
        new_b_start - 1, new_a_end - 1, both + 1, new_ab
      else
      new_b_start, new_a_end, both, new_ab)
    (0, 0, 0, 0)
    ss
  in
    let pair = min b_start a_end in
    let need = max b_start a_end - pair in
    let addition = if both <= need then
        pair + both
      else
        (* pair + need + (both - need + 1) / 2 in *)
        pair + need + (both - need) in
    addition + ab

(* O(n) *)
let rec fold_btw f a i n = if i >= n then a else fold_btw f (f a i) (i + 1) n
let fold_int f a n = fold_btw f a 0 n

let _ =
  let n = read_int () in
  fold_int
    (fun acc _ -> read_line () :: acc)
    []
    n |> solve n |> string_of_int |> print_endline