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 C++ (GCC 9.2.1) (judge verdict: Accepted)

#include <bits/stdc++.h>
#define rep(i, n) for(long long int i = 0; i < n; i++)
#define _rep(i, m, n) for(long long int i = m; i < n; i++)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int MAX_N = 100010;
const ll mod = 1000000007;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

ll gcd(ll A, ll B){
    if(B == 0)return A;
    return gcd(B, A % B);
}
ll lcm(ll A, ll B){
    return A * B / gcd(A, B);
}

/*------------------------------------------------------------------*/
int main(){
    int n; cin >> n;
    
    int count = 0;
    int coa = 0, cob = 0, coab = 0;
    string s;

    for(int i = 0; i < n; i++){
        cin >> s;
        for(int j = 0; j < s.length() - 1; j++){
            if(s[j] == 'A' and s[j + 1] == 'B') count++;
        }
        if(s[0] == 'B' and s[s.length() - 1] != 'A') coa++;
        if(s[0] != 'B' and s[s.length() - 1] == 'A') cob++;
        if(s[0] == 'B' and s[s.length() - 1] == 'A') coab++; 
    }
    if(coab == 0){
        cout << count + min(coa, cob) << endl;
    }else if(coa + cob != 0){
        cout << count + min(coa, cob) + coab << endl; 
    }else if(coa + cob == 0){
        cout << count + coab - 1 << endl;
    }
    return 0;
}