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.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;


public class Main {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Scanner sc = new Scanner(System.in);
		int N = Integer.parseInt(sc.next());
		boolean flag = true;
		int ans = 0;
		int count_XXA=0;
		int count_BXX=0;
		//String[] s = new String[N];
		for(int i=0; i<N; i++){
			//s[i] = sc.next();
			String str = sc.next();
			ans += count_AB(str);
			if(is_XXA(str))count_XXA++;
			if(is_BXX(str))count_BXX++;
			flag = flag && is_BXXA(str);
		}
		
		if(N>1)ans += Math.min(count_XXA, count_BXX);
		if(flag)ans--;

		System.out.println(ans);
		
		
		sc.close();
	}
	
	public static int count_AB(String str){
		int count=0;
		char[] c = str.toCharArray();
		int len=c.length;
		for(int i=0; i<len-1;i++){
			if(c[i]=='A' && c[i+1]=='B')count++;
		}
		return count;
	}
	
	public static boolean is_BXXA(String str){
		char[] c = str.toCharArray();
		int len=c.length;
		return c[0]=='B' && c[len-1]=='A';
	}
	
	public static boolean is_BXX(String str){
		char[] c = str.toCharArray();
		return c[0]=='B';
	}
	
	public static boolean is_XXA(String str){
		char[] c = str.toCharArray();
		int len=c.length;
		return c[len-1]=='A';
	}
	
}