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>

typedef long long int ll;
typedef unsigned long long int ull;
#define rep(i,n) for(auto i=0;i<(n);i++)
#define rep1(i,n) for(auto i=1;i<=(n);i++)
#define all(x) (x).begin(),(x).end()

using namespace std;


struct init{ init(){ cin.tie(0); ios::sync_with_stdio(0); cout<<fixed<<setprecision(20); }; }aaaaaaa;


int main(){
  ll n;
  cin >> n;
  vector<string> list(n);
  rep(i, n) cin >> list[i];


  ll res = 0;
  rep(i, n){
    rep(j, (ll)list[i].size()-1){
      if(list[i][j] == 'A' && list[i][j+1] == 'B') res++;
    }
  }

  vector<string> keys = {"BA", "XA", "BX"};
  map<string, ll> ma;
  ll sum = 0;
  rep(i, n){
    string s = "";
    s += list[i][0];
    s += list[i].back();
    
    if(s == "BA")             ma["BA"]++, list[i] = "BA";
    else if(s.back() == 'A')  ma["XA"]++, list[i] = "XA";
    else if(s[0] == 'B')      ma["BX"]++, list[i] = "BX";
  }

  if(0 < ma["BA"]){
    ll d = ma["BA"]-1;
    res += d;
    ma["BA"] -= d;
  }

  if(0 < max(ma["XA"], ma["BX"]) && 0 < ma["BA"]){
    ll e = ma["BA"];
    res += e;
    ma["BA"] -= e;
  }

  ll f = min(ma["XA"], ma["BX"]);
  res += f;
  ma["XA"] -= f;
  ma["BX"] -= f;
  
  cout << res << endl;

  
  return 0;
}