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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.util.StringTokenizer;

class Main{
	public static void main(String[] args) {
		SC sc=new SC(System.in);
		int N=sc.nextInt();
		int ao=0;
		int bh=0;
		int ab=0;
		int no=0;
		String[] s=new String[N];
		for(int i=0; i<N; i++) {
			s[i]=sc.next();
			if(s[i].charAt(0)=='B' && s[i].charAt(s[i].length()-1)=='A') {
				ab++;
			}
			else if(s[i].charAt(0)=='B') {
				bh++;
			}
			else if(s[i].charAt(s[i].length()-1)=='A') {
				ao++;
			}
			else {
				no++;
			}
		}
		int add=Math.min(ao,bh);
		int diff=Math.max(ao, bh)-Math.min(ao, bh);
		int di2=0;
		if(diff>ab) {
			di2=ab;
		}
		else {
			di2=diff;
			di2+=Math.max((ab-diff)-1,0);
		}
		add+=di2;
		int base=0;
		for(int i=0; i<N; i++) {
			int nagasa=s[i].length();
			for(int j=0; j<nagasa-1; j++) {
				if(s[i].charAt(j)=='A' && s[i].charAt(j+1)=='B') {
					base++;
				}
			}
		}
		pl(base+add);
	}
	static class SC {
		private BufferedReader reader = null;
		private StringTokenizer tokenizer = null;
		public SC(InputStream in) {
			reader = new BufferedReader(new InputStreamReader(in));
		}
		public String next() {
			if (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new UncheckedIOException(e);
				}
			}
			return tokenizer.nextToken();
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
	}
	public static void pl(Object o) {
		System.out.println(o);
	}
}