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: Wrong Answer)

#include <bits/stdc++.h>

#define REP(i, x, n) for (int i = x; i < (int)(n); i++)
#define rep(i, n) REP(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)(x.size())
#define popcount(x) __builtin_popcount(x)
#define popcountll(x) __builtin_popcountll(x)
#define uniq(x) x.erase(unique(x.begin(), x.end()), x.end())
#define F first
#define S second
#define mp make_pair
#define eb emplace_back
#define pii pair<int, int>
#define pll pair<ll, ll>

using namespace std;

typedef long long ll;

/* --- INFの値が適切か確認する --- */
// const int INF = 1 << 30;
// const ll INF = 1LL << 60;
// const int MOD = 1000000007;

int main() {
  int n;
  cin >> n;
  int ans = 0;
  int ba = 0, a = 0, b = 0;
  rep(i, n) {
    string s;
    cin >> s;
    if (s[0] == 'B' && s[sz(s) - 1] == 'A')
      ba++;
    else if (s[0] == 'B')
      b++;
    else if (s[sz(s) - 1] == 'A')
      a++;

    rep(j, sz(s) - 1) if(s[j] == 'A' && s[j + 1] == 'B') ans++;
  }
  int t = min({ba, a, b});
  ans += 2 * t;
  ba -= t;
  a -= t;
  b -= t;
  if (ba == 0) {
    ans += min(a, b);
  } else {
    if (a == 0 && b == 0) {
      if (ba > 1) ans += ba - 1;
    }
    else if (a == 0) {
      t = min(b, ba);
      ans += t;
      ba -= t;
      if (ba > 0) ans += ba;
    } else {
      t = min(a, ba);
      ans += t;
      ba -= t;
      if (ba > 0) ans += ba;
    }
  }
  cout << ans << endl;
}