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 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include <stdio.h>
#include <string.h>

int min(int a,int b){
	if(a<=b){return a;}
	return b;
}

int main(void){
	int N;
	scanf("%d",&N);
	int size;
	int inAB=0;
	int fA=0;
	int fB=0;
	int bA=0;
	int bB=0;
	int AB;
	int a,b,c,d;
	int AoA,AoB,BoA,BoB;
	AoA=0;
	AoB=0;
	BoB=0;
	BoA=0;

	char s[N][11];
	for(int i=0; i<N; i++){
		scanf("%s",s[i]);
	}

	for(int i=0; i<N; i++){
		size=strlen(s[i]);	
		a=0; b=0; c=0; d=0;
		for(int j=0;s[i][j]!='\0'; j++){
			if(s[i][j]=='A' && s[i][j+1]=='B'){ inAB++; }
			else if(j==0 && s[i][j]=='A'){ fA++; a=1;}
			else if(j==0 && s[i][j]=='B'){ fB++; b=1;}
			else if(j==size-1 && s[i][j]=='A'){ bA++; c=1;}
			else if(j==size-1 && s[i][j]=='B'){ bB++; d=1;}
		}
		if(a==1 && c==1){ AoA++; }
		if(a==1 && d==1){ AoB++; }
		if(b==1 && c==1){ BoA++; }
		if(b==1 && d==1){ BoB++; }

	}
	printf("%d %d %d %d %d\n",inAB,fA,fB,bA,bB );
	AB=inAB+min(fA,bB)+min(fB,bA);
	if(AoA>0 && (fA==0 && bA==0)){AB=AB-AoA;}
	if(AoB>0 && (fA==0 && bB==0)){AB=AB-AoB;}
	if(BoA>0 && (fB==0 && bA==0)){AB=AB-BoA;}
	if(BoB>0 && (fB==0 && bB==0)){AB=AB-BoB;}
	printf("%d\n",AB );
}