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: Time Limit Exceeded)

#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define repr(i,a,b) for(int i=(int)(a);i>(int)(b);i--)
#define MM 1e9

int N;
string s;
vector<string> v;
long long res=0;

void input() {
    cin >> N;
    rep(i,0,N) {
        cin >> s;
        if (s.find("A") != std::string::npos || s.find("B") != std::string::npos)
        v.push_back(s);
    }
}

void solve(){
    vector<int> vp(v.size());
    string str;
    int res=0;
    iota(vp.begin(), vp.end(), 1);
    do {
        str = "";
        for (auto x:vp) str += v.at(x-1);
        //cout << "----" << str << endl;
        int LEN=str.length();
        int cnt=0;
        rep(i,0,LEN) {
            if (i+1>=LEN) break;
            //cout << str.substr(i,2) << " ";
            if (str.substr(i,2)=="AB") cnt++;
        }
        //cout << endl;
        res=max(res,cnt);
    } while (next_permutation(vp.begin(),vp.end()));
    cout << res << endl;
}

int main() {
    input();
    solve();
}