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 Scala (2.11.7) (judge verdict: Accepted)

import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val n = in.readLine().toInt
    val ss = Array.fill(n) {
      in.readLine()
    }

    var count = ss.foldLeft(0) {
      case (acc, s) => acc + s.foldLeft((0, false)) {
        case ((acc, stat), c) => if (c == 'A') {
          (acc, true)
        } else if (stat && c == 'B') {
          (acc + 1, false)
        } else {
          (acc, false)
        }
      }._1
    }

    var ab = ss.count(s => s.startsWith("B") && s.endsWith("A"))
    var a = ss.count(s => !s.startsWith("B") && s.endsWith("A"))
    var b = ss.count(s => s.startsWith("B") && !s.endsWith("A"))
    var continuous = true

    while (continuous) {
      if (a > 0 && ab > 0) {
        val diff = Math.min(ab, a)
        ab -= diff
        count += diff
      } else if (b > 0 && ab > 0) {
        val diff = Math.min(ab, b)
        ab -= diff
        count += diff
      } else if (a > 0 && b > 0) {
        val diff = Math.min(a, b)
        a -= diff
        b -= diff
        count += diff
      } else if (ab > 1) {
        count += ab - 1
        ab = 1
      } else {
        continuous = false
      }
    }

    out.println(count)

    out.flush()
  }
}