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 <stdlib.h>//random,NULL
#include <string.h>
#include <time.h>
#include <unistd.h>//sleep()
#include <math.h>
#include <stdbool.h>

#define rep(i,n) for(int i=0; i<((int)n); i++)
#define REP(i,n) for(int i=0; i<=((int)n); i++)
#define srep(i,a,n) for(int i=a; i<((int)n); i++)
#define SREP(i,a,n) for(int i=a; i<=((int)n); i++)
#define rrep(i,n) for(int i=n-1; i>=0; i--)
#define RREP(i,n) for(int i=n; i>=0; i--)
#define INF 1000000000

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

int main(){
  char buf[1024];
  int N;

  fgets(buf,sizeof(buf),stdin);
  sscanf(buf, "%d", &N);

  char **s=(char **)malloc(sizeof(char *)*N);
  rep(i,N){
    s[i]=(char *)malloc(sizeof(char)*10);
  }

  rep(i,N){
    fgets(buf,sizeof(buf),stdin);
    sscanf(buf, "%s", s[i]);
  }

  int in_count=0;
  int A_count=0;
  int B_count=0;
  bool flag=true;//全てがA_Bの組

  rep(i,N){
    int l=strlen(s[i]);
    srep(j,1,l){
      if(s[i][j-1]=='A' && s[i][j]=='B'){
        in_count++;
      }
    }
    if(s[i][0]=='B' && s[i][l-1]=='A'){
      A_count++;
      B_count++;
    }
    else if(s[i][0]=='B'){
      B_count++;
      flag=false;
    }
    else if(s[i][l-1]=='A'){
      A_count++;
      flag=false;
    }
  }

  int ans;

  if(flag==true){
    ans=in_count+A_count-1;
  }
  else{
    ans=in_count+min(A_count, B_count);
  }

  printf("%d\n", ans);

  return 0;

}