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

#include <bits/stdc++.h>
#define ll long long
#define rep(i,n) for(int i=0;i<n;i++)
#define Rep(i,a,b) for(int i=a;i<b;i++)
#define REP(i,a,b) for(int i=a;i<=b;i++)
#define rev(i,n) for(int i=n-1;i>=0;i--)
#define vi vector<int>
#define vv vector<vi>
#define pb push_back
#define pi pair<int,int>
#define vp vector<pair<int,int> >
#define mp make_pair
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
#define INF 100000000000
#define eps 1e-7
#define mod 1000000007
#define int ll
using namespace std;
int N;
string moji[10000];
int AB = 0;
int Alast = 0;
int Bfirst = 0;
int same = 0;

signed main(void) {
    cin >> N;
    rep(i,N){
        cin >> moji[i];

        rep(j,moji[i].size()){
            if(moji[i][j] == 'A' && moji[i][j+1] == 'B'){
                AB++;
            }
        }

        if(moji[i][moji[i].size()-1] == 'A'){
            Alast++;
        }

        if(moji[i][0] == 'B'){
            Bfirst++;
        }

        if(moji[i][moji[i].size()-1] == 'A' && moji[i][0] == 'B'){
            same++;
        }
    }


    if(same == max(Alast, Bfirst) && same > 0){
        cout << AB + min(Alast, Bfirst) - 1 << endl;
    }else{
        cout << AB + min(Alast, Bfirst) << endl;
    }


    return 0;
}