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 Java8 (OpenJDK 1.8.0) (judge verdict: Wrong Answer)

import java.util.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class Main {
	int endA = 0, startB = 0, both = 0, contain = 0;
	int result = 0;

	Main(List<String> list) {
		for (int i = 0; i < list.size(); ++i) {
			String str = list.get(i);
			if (str.endsWith("A") && str.startsWith("B")) {
				++both;
			} else if (str.endsWith("A")) {
				endA++;
			} else if (str.startsWith("B")) {
				startB++;
			}
			if (str.contains("AB")) {
				for (int j = 0; j < str.length() - 1; ++j) {
					if (str.substring(j, j + 2).equals("AB")) {
						++contain;
					}
				}
			}
		}
		result += contain;
		result += Math.max(both - 1, 0);
		if (endA > 0) {
			result++;
			endA--;
		}
		if (startB > 0) {
			result++;
			startB--;
		}
		result += Math.min(endA, startB);
	}

	public static void main(String[] args) throws IOException {
		InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
		BufferedReader in = new BufferedReader(reader);
		int N = Integer.parseInt(in.readLine());
		List<String> list = new ArrayList<>();
		for (int i = 0; i < N; ++i) {
			list.add(in.readLine());
		}

		in.close();
		Main main = new Main(list);
		System.out.println(main.result);
	}

}