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: Runtime Error)

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>

using namespace std;

int main(){
	int N; cin >> N;
	vector<string> S(N);
	vector<int> enda, beginb, btoa;

	int cnt = 0;

	for(int i = 0; i < N; ++i) cin >> S[i];

	for(int i = 0; i < N; ++i){
		int begin = 0, end = S[i].size()-1;
		if(S[i][begin] == 'B' && S[i][end] == 'A') btoa.push_back(i);
		else if(S[i][end] == 'A') enda.push_back(i);
		else if(S[i][begin] == 'B') beginb.push_back(i);
	}

	for(int i = 0; i < btoa.size(); ++i){
		if(i > enda.size()) break;
		int e = enda[i], b = btoa[i];
		S[e] = S[e] + S[b];
		S[b] = "";
	}

	int tmpi = 0;
	while(enda.size() > tmpi){
 		int i = tmpi;

		for(int j = 0; j < beginb.size(); ++j){
			int e = enda[i], b = beginb[j];
			if(e != b && b != -1 && e != -1){
				S[e] = S[e] + S[b];
				S[b] = "";
				if(S[e][S[i].size()-1] == 'A') enda.push_back(i);
				vector<int>::iterator iter = find(enda.begin(), enda.end(), b);
				if(iter != enda.end()){
					enda[distance(enda.begin(), iter)] = -1;
				}
				beginb[j] = -1;
				
				break;
			}
		}
		tmpi++;
	}

	// cout << endl;
	for(int i = 0; i < N; ++i){
		// cout << "i:" << i << ", " << S[i] << endl;
		for(int j = 0; j < S[i].size(); ++j){
			if(S[i][j] == 'A' && S[i][j+1] == 'B') cnt++;
		}
	}

	cout << cnt << endl;


	return 0;
}