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: Accepted)

package main

import (
	"fmt"
)

func max(nums ...int) int {
	ret := nums[0]
	for _, v := range nums {
		if v > ret {
			ret = v
		}
	}
	return ret
}

func min(nums ...int) int {
	ret := nums[0]
	for _, v := range nums {
		if v < ret {
			ret = v
		}
	}
	return ret
}

func main() {
	var n int
	fmt.Scan(&n)
	s := make([]string, n)
	for i := range s {
		fmt.Scan(&s[i])
	}

	BtoA := 0
	headB := 0
	tailA := 0
	containAB := 0
	for i := range s {
		head := s[i][0]
		tail := s[i][len(s[i])-1]
		if head == 'B' && tail == 'A' {
			BtoA++
		} else if head == 'B' {
			headB++
		} else if tail == 'A' {
			tailA++
		}
		for j := 0; j < len(s[i])-1; j++ {
			if s[i][j:j+2] == "AB" {
				containAB++
			}
		}
	}

	ans := containAB
	if headB+tailA == 0 {
		ans += max(0, BtoA-1)
	} else {
		ans += BtoA + min(headB, tailA)
	}
	fmt.Println(ans)
}