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 Go (1.6) (judge verdict: Wrong Answer)

package main

import (
	"fmt"
	"strings"
)

func main() {
	var n int
	fmt.Scan(&n)

	var tailA int
	var headB int
	var both int
	var ret int
	for i := 0; i < n; i++ {
		var s string
		fmt.Scan(&s)

		ret += strings.Count(s, "AB")
		if s[0] == 'B' && s[len(s)-1] == 'A' {
			both++
		} else if s[0] == 'B' {
			headB++
		} else if s[len(s)-1] == 'A' {
			tailA++
		}
	}

	if both >= tailA && both >= headB {
		ret += both - 1
		if both > 0 && tailA > 0 {
			ret += 1
			tailA -= 1
		}
		if both > 0 && headB > 0 {
			ret += 1
			headB -= 1
		}
		if tailA > headB {
			ret += headB
		} else {
			ret += tailA
		}
	} else if headB > both && both >= tailA {
		ret += tailA * 2
		restBoth := both - tailA
		restHeadB := headB - tailA
		if restBoth > 0 {
			ret += restBoth - 1
			if restHeadB > 0 {
				ret += 1
			}
		}
	} else if tailA > both && both >= headB {
		ret += headB * 2
		restBoth := both - headB
		restTailA := tailA - headB
		if restBoth > 0 {
			ret += restBoth - 1
			if restTailA > 0 {
				ret += 1
			}
		}
	} else {
		ret += both * 2
		restTailA := tailA - both
		restHeadB := headB - both
		if restTailA > restHeadB {
			ret += restHeadB
		} else {
			ret += restTailA
		}
	}

	fmt.Println(ret)
}