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# (Mono 4.6.2.0) (judge verdict: Wrong Answer)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DIVERTA2019C
{
    class Program
    {
        static int includeOf(string src, string target)
        {
            int count = 0;

            int index = src.IndexOf(target, 0);
            while (index >= 0)
            {
                count++;
                index = src.IndexOf(target, index + target.Length);
            }

            return count;
        }

        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            var input = Enumerable.Range(0, n)
                .Select(_ => Console.ReadLine()).ToList();

            var includeCount = 0;
            var endCount = 0;
            var startCount = 0;
            var bothCount = 0;
            foreach (var s in input)
            {
                // 文字列中のAB数
                includeCount += includeOf(s, "AB");

                // 末尾がA
                var lastChar = s.Last();
                if (lastChar == 'A')
                {
                    endCount++;
                }
                // 先頭がB
                var startChar = s.First();
                if (startChar == 'B')
                {
                    startCount++;
                }
                // 先頭がBで末尾がA
                if (startChar == 'B' && lastChar == 'A')
                {
                    bothCount++;
                }
            }

            var unionCount = Math.Min(startCount, endCount);
            var output = includeCount + unionCount;

            // 単純に数えるだけだと、「B***A」みたいな単語でおかしくなるので調整
            if (output > 0 && (bothCount == Math.Max(startCount, endCount)))
            {
                output--;
            }

            Console.WriteLine(output);
        }
    }
}