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 (7.3.0) (judge verdict: Runtime Error)

#!/usr/bin/env python3
import collections as cl
import sys


def II():
    return int(sys.stdin.readline())


def MI():
    return map(int, sys.stdin.readline().split())


def LI():
    return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()

    words = []
    starts_with_B = 0
    end_with_A = 0
    contain_AB = 0
    starts_with_B_and_end_with_A = 0
    for i in range(N):
        word = input()
        words.append(word)
        contain_AB += len(word) - len(word.replace("AB", "_"))

        if word[0] == "B" and word[-1] == "A":
            starts_with_B_and_end_with_A += 1
        elif word[0] == "B":
            starts_with_B += 1
        elif word[-1] == "A":
            end_with_A += 1

    if starts_with_B_and_end_with_A == 0:
        print(contain_AB + min(starts_with_B, end_with_A))
        return

    min_A_or_B = min(starts_with_B, end_with_A)
    amari = abs(starts_with_B - end_with_A)
    contain_AB += min_A_or_B

    if amari == 0:
        print(contain_AB)

    if amari >= starts_with_B_and_end_with_A:
        print(contain_AB + starts_with_B_and_end_with_A)
    else:
        available = starts_with_B_and_end_with_A // amari
        contain_AB += available * amari
        starts_with_B_and_end_with_A = starts_with_B % amari
        print(contain_AB + starts_with_B_and_end_with_A)


main()