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 PyPy3 (2.4.0) (judge verdict: Accepted)

# diverta 2019 Programming Contest
# https://atcoder.jp/contests/diverta2019
import sys

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in list(ss)]
ss2nnn = lambda ss: [s2nn(s) for s in list(ss)]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N = i2n()
    S = ii2ss(N)
    c0b = 0
    c1a = 0
    c0b1a = 0
    c = 0
    for s in S:
        for i, t in enumerate(s[:-1]):
            if t == 'A':
                if s[i+1] == 'B':
                    c += 1
        if s[0] == 'B' and s[-1] == 'A':
            c0b1a += 1
        elif s[0] == 'B':
            c0b += 1
        elif s[-1] == 'A':
            c1a += 1
    c0b1a_min = min(c0b, c1a)
    c += c0b1a_min
    if c0b1a > 0:
        if c0b > 0 or c1a > 0:
            c += c0b1a
        else:
            c += c0b1a - 1
    print(c)

main()