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 Ruby (2.3.3) (judge verdict: Wrong Answer)

def find_ab(str)
    return str.include?('A') || str.include?('B')
end

N = (gets).to_i
strs = []
N.times do
    strs << gets.strip.gsub(/[^AB]+/, "-")
end
strs.select! { |a| (a.length > 0) && find_ab(a) }
#puts strs
strs.sort!

state = false # falseのときAで終わるひとを探す、tureのときBで始まる人を探す
isLoop = true
ret_str = ""
while isLoop
    isLoop = !state # stateがfalseのときは抜けないようにする
    strs.each.with_index do |str, i|
        if state then
            if str=~/^B/ then
                ret_str << str
                #puts "^B : " + str
                strs.delete_at(i)
                isLoop = true
                break # 一度抜ける
            end
        else
            if str=~/A$/ then
                ret_str << str
                #puts "A$ : " + str
                strs.delete_at(i)
                isLoop = true
                break
            end
        end
    end
    state = !state
end
# あまったやつはくっつけておく
strs.each {|s| ret_str << s}

#puts ret_str

count = 0
index = -1
while true
    index = ret_str.index("AB", index+1)
    break if index.nil?
    count += 1
end

puts count