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 s, int t);
int max(int s, int t);

int main(void){
  int i, j;
  int n;
  int endA=0, startB=0, BA=0;
  int AB=0;
  int mi, ma, sa;
  int L;//文字列の数

  scanf("%d", &n);
  char str[n][11];

  for(i=0; i<n; i++){
    scanf("%s", str[i]);
  }

  for(i=0; i<n; i++){
     L=strlen(str[i]);
     for(j=0; j<L; j++){
       if((str[i][j]=='B')&&j!=0){
         if(str[i][j-1]=='A') AB++;
       }
     }
     if(str[i][0]=='B'){
       if(str[i][L-1]=='A'){
         BA++;
       }else{
         startB++;
       }
     }
     if(str[i][L-1]=='A') endA++;
  }

  // printf("startB=%d endA=%d BA=%d\n", startB, endA, BA);

  if(BA==0){
    AB+=min(startB, endA);
  }else{
    mi=min(startB, endA);
    ma=max(startB, endA);
    sa=ma-mi;
    if(sa>=BA){
      AB+=mi+BA;
    }else{
      AB+=mi+sa+(BA-sa)/2;
    }
  }

  // printf("AB=%d\n", AB);
  printf("%d\n", AB);

  // for(i=0; i<n; i++){
  //   printf("i=%d %s\n", i,str[i]);
  // }
  // for(i=0; i<n; i++){
  //   L=strlen(str[i]);
  //   printf("i=%d L=%d\n", i, L);
  // }
  return 0;
}

int min(int s, int t){
  if(s>t){
    return t;
  }else{
    return s;
  }
}
int max(int s, int t){
  if(s>t){
    return s;
  }else{
    return t;
  }
}