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



Sample input:
3
ABCA
XBAZ
BAD


Sample output:
2

Submission status: Wrong Answer

Solution code:
n=int(input())
a,b,ans=0,0,0
for _ in range(n):
    s=input()
    for i in range(len(s)-1):
        if s[i]=="A" and s[i+1]=="B": ans+=1
    if s[0]=="B": b+=1
    if s[-1]=="A": a+=1
print(ans+min(a,b))

Submission status: Wrong Answer

Solution code:
n = int(input())
a_end_count = 0
b_start_count = 0
ab_count = 0
a_or_b_count = 0
for _ in range(n):
  s = input()
  if s[-1] == 'A':
    a_end_count += 1
  if s[0] == 'B':
    b_start_count += 1
  if s[-1] == 'A' or s[0] == 'B':
    a_or_b_count += 1
  ab_count += s.count('AB')
ab_count += min([a_or_b_count - 1, a_end_count, b_start_count])
print(ab_count)

Submission status: Wrong Answer

Solution code:
n = int(input())
a_end_count = 0
b_start_count = 0
ab_count = 0
for _ in range(n):
  s = input()
  if s[-1] == 'A':
    a_end_count += 1
  if s[0] == 'B':
    b_start_count += 1
  ab_count += s.count('AB')
ab_count += min([n - 1, a_end_count, b_start_count])
print(ab_count)

Submission status: Wrong Answer

Solution code:
n = int(input())
ab,a,b = 0,0,0
for i in range(n):
    s = input()
    if "AB" in s:
        ab +=1
    if s[0] == "B":
        b +=1
    if s[-1] == "A":
        a +=1
print(ab + min(a,b))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
a = 0
b = 0
ab = 0
for i in range(n):
    if s[i][0] == "B" and s[i][-1] == "A":
        ab += 1
    elif s[i][0] == "B":
        b += 1
    elif s[i][-1] == "A":
        a += 1
c = min(a, b)
ans = c
if ab > 0:
    ans += ab
if a== 0 and b==0 and not ab: #not abは盲点
    ans = ab - 1
for S in s:
    for i in range(len(S)-1):
        if S[i: i + 2] == "AB":
            ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
a = 0
b = 0
ab = 0
for i in range(n):
    if s[i][0] == "B" and s[i][-1] == "A":
        ab += 1
        a += 1
        b += 1
    elif s[i][0] == "B":
        b += 1
    elif s[i][-1] == "A":
        a += 1
c = min(a, b)
ans = c
if ab > 0:
    ans += ab
if a== 0 and b==0:
    ans = ab - 1
for S in s:
    for i in range(len(S)-1):
        if S[i: i + 2] == "AB":
            ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
a = 0
b = 0
ab = 0
for i in range(n):
    if s[i][0] == "B" and s[i][-1] == "A":
        ab += 1
    elif s[i][0] == "B":
        b += 1
    elif s[i][-1] == "A":
        a += 1
c = min(a, b)
ans = c
if ab > 0:
    ans += ab
if a== 0 and b==0:
    ans = ab - 1
for S in s:
    for i in range(len(S)-1):
        if S[i: i + 2] == "AB":
            ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
Count_A = 0
Count_B = 0
Count_BA = 0
s = []
for _ in range(N):
    s.append(input())

for i in range(N):
    ans += s[i].count("AB")
    if s[i][0] == "B" and s[i][-1] == "A":
        Count_BA += 1
    elif s[i][0] == "B":
        Count_B += 1
    elif s[i][-1] == "A":
        Count_A += 1

if Count_BA == 0:
    ans += min(Count_A, Count_B)
elif Count_A == Count_B:
    ans += Count_BA-1 + min(Count_A, Count_B)
else:
    ans += Count_BA-1 + min(Count_A, Count_B) + 1

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
a = 0
b = 0
ab = 0
for i in range(n):
    if s[i][0] == "B" and s[i][-1] == "A":
        ab += 1
    elif s[i][0] == "B":
        b += 1
    elif s[i][-1] == "A":
        a += 1
#場合分けの考察が不十分だった
c = min(a, b)
ans = c
if ab > 0:
    ans += ab
if ab == n:
    ans = n - 1
for S in s:
    for i in range(len(S)-1):
        if S[i: i + 2] == "AB":
            ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
a = 0
b = 0
ab = 0
for i in range(n):
    if s[i][0] == "B" and s[i][-1] == "A":
        ab += 1
        a += 1
        b += 1
    elif s[i][0] == "B":
        b += 1
    elif s[i][-1] == "A":
        a += 1
c = min(a, b)
ans = c
if ab == n:
    ans = n - 1
for S in s:
    for i in range(len(S)-1):
        if S[i: i + 2] == "AB":
            ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
a = 0
b = 0
ab = 0
for i in range(n):
    if s[i][0] == "B" and s[i][-1] == "A":
        ab += 1
        a += 1
        b += 1
    elif s[i][0] == "B":
        b += 1
    elif s[i][-1] == "A":
        a += 1
c = min(a, b)
ans = c
if ab == n:
    ans = n - 1
for S in s:
    for i in range(len(s)-1):
        if S[i: i + 2] == "AB":
            ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

N = INT()

ans = 0
a = 0
b = 0
ba = 0

for _ in range(N):
	s = input()
	ans += s.count("AB")
	if s[0] == "B" and s[-1] == "A":
		ba += 1
	elif s[0] == "B":
		b += 1
	elif s[-1] == "A":
		a += 1

ans += ba-1 + (0<a) + (0<b) 

if 0 < min(a-1, b-1):
	ans += min(a-1, b-1)


print(max(ans, 0))

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

N = INT()

ans = 0
a = 0
b = 0
ba = 0

for _ in range(N):
	s = input()
	ans += s.count("AB")
	if s[0] == "B" and s[-1] == "A":
		ba += 1
	elif s[0] == "B":
		b += 1
	elif s[-1] == "A":
		a += 1

ans += ba-1 + (0<a) + (0<b) 

if 0 < min(a-1, b-1):
	ans += min(a-1, b-1)


print(ans)

Submission status: Wrong Answer

Solution code:
xa = 0
bx = 0
ba = 0
ans = 0
N = int(input())

for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            ba += 1
        else:
            bx += 1
    elif s[-1] == "A":
        xa += 1

if xa+bx == 0:
    ans += ba-1
else:
    ans += ba+min(xa,bx)


print(ans)

Submission status: Wrong Answer

Solution code:
xa = 0
bx = 0
ba = 0
ans = 0
N = int(input())

for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            ba += 1
        else:
            bx += 1
    elif s[-1] == "A":
        xa += 1

if xa+bx == 0:
    ans += ba-1
else:
    ans += ba+min(xa,bx)

Submission status: Wrong Answer

Solution code:
xa = 0
bx = 0
ba = 0
ans = 0
N = int(input())

for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        ba += 1
    elif s[0] == "B":
        bx += 1
    elif s[-1] == "A":
        xa += 1

if xa == 0 and bx == 0:
    ans += ba-1
else:
    ans += ba+min(xa,bx)


print(ans)

Submission status: Wrong Answer

Solution code:
xa = 0
bx = 0
ba = 0
ans = 0
N = int(input())
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        ba += 1
    elif s[0] == "B":
        bx += 1
    elif s[-1] == "A":
        xa += 1

if xa+bx == 0:
    ans += ba-1
else:
    ans += ba+min(xa,bx)


print(ans)

Submission status: Wrong Answer

Solution code:
xa = 0
bx = 0
ba = 0
ans = 0
N = int(input())
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        ba += 1
    elif s[0] == "B":
        bx += 1
    elif s[-1] == "A":
        xa += 1

if xa+bx == 0:
    ans += ba-1
else:
    ans += ba+min(xa,bx)

Submission status: Wrong Answer

Solution code:
n = int(input())
count = 0
l = [input() for i in range(n)]
a = 0
b = 0
ab = 0
for i in range(n):
    if "AB" in l[i]:
        count += l[i].count("AB")
    if l[i][0] == "B" and l[i][-1] == "A":
        ab += 1
    elif l[i][0] == "B":
        b += 1
    elif l[i][-1] == "A":
        a += 1
x= min(ab,b)
count += x
b -= x
x= min(ab,a)
count += x
a -= x
if a and b:
    count += min(a,b)
print(count)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

N = int(input())
S = [input() for i in range(N)]

ret = 0

for s in S:
    ret += s.count('AB')

D = [0] * N
for i in range(N):
    r = [0, 0]
    if S[i][0] == 'B':
        r[0] = 1
    if S[i][-1] == 'A':
        r[1] = 1

    D[i] = r

b_c = D.count([1, 0])
a_c = D.count([0, 1])
ab_c = D.count([1, 1])

nokori = 0
if b_c > a_c:
    nokori = b_c - a_c
    ret += a_c + min(ab_c, nokori)
else:
    nokori = a_c - b_c
    ret += b_c + min(ab_c, nokori)

if ab_c > nokori:
    ret += ab_c - nokori

print(ret)

Submission status: Wrong Answer

Solution code:
N = int(input())
AB = 0
A = 0
B = 0
for i in range(N):
    s = list(input())
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            AB += 1
    if s[-1] == 'A':
        A += 1
    if s[0] == 'B':
        B += 1
AB += min(A,B,N-1)
print(AB)

Submission status: Wrong Answer

Solution code:
from math import ceil
N = int(input())
AB = 0
A = 0
B = 0
for i in range(N):
    s = list(input())
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            AB += 1
    if s[-1] == 'A':
        A += 1
    if s[0] == 'B':
        B += 1
AB += min(A,B,ceil(N/2))
print(AB)

Submission status: Wrong Answer

Solution code:
N = int(input())
AB = 0
A = 0
B = 0
for i in range(N):
    s = list(input())
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            AB += 1
    if s[-1] == 'A':
        A += 1
    if s[0] == 'B':
        B += 1
AB += min(A,B,(N+1)//2)
print(AB)

Submission status: Wrong Answer

Solution code:
N = int(input())
AB = 0
A = 0
B = 0
for i in range(N):
    s = list(input())
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            AB += 1
    if s[-1] == 'A':
        A += 1
    if s[0] == 'B':
        B += 1
AB += min(A,B)
print(AB)

Submission status: Wrong Answer

Solution code:
a = 0
b = 0
ab = 0
N = int(input())
for _ in range(N):
    s = input()
    ab += s.count("AB")
    a += (s[-1] == "A")
    b += (s[0] == "B")

a = min(a,N-1)
b = min(b,N-1)

print(ab+min(a,b))

Submission status: Wrong Answer

Solution code:
a = 0
b = 0
ab = 0

for _ in range(int(input())):
    s = input()
    ab += s.count("AB")
    a += (s[-1] == "A")
    b += (s[0] == "B")

print(ab+min(a,b))

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[""]*N
for i in range(N):
    S[i]=input()

H=0
A,B=0,0
for s in S:
    for j in range(len(s)-1):
        if s[j:j+2]=="AB":
            H+=1

    if s[-1]=="A":
        A+=1
    if s[0]=="B":
        B+=1

A=min(N-1,A)
B=min(N-1,B)
print(H+min(A,B))

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[""]*N
for i in range(N):
    S[i]=input()

H=0
A,B=0,0
for s in S:
    for j in range(len(s)-1):
        if s[j:j+2]=="AB":
            H+=1

    if s[-1]=="A":
        A+=1
    if s[0]=="B":
        B+=1

print(H+min(A,B))

Submission status: Wrong Answer

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
from operator import mul

INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 組合せnCr
def combinations_count(n, r):
    if n < r:
        return 0
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

# ここから書き始める
n = int(input())
s = [input() for i in range(n)]

cnt1 = 0
cnt2 = 0
cnt3 = 0
ans = 0
for i in s:
    ans += i.count("AB")
    if i[0] == "B" and i[-1] == "A":
        cnt1 += 1
    elif i[0] == "B":
        cnt2 += 1
    elif i[-1] == "A":
        cnt3 += 1

# print("cnt1 =", cnt1)
# print("cnt2 =", cnt2)
# print("cnt3 =", cnt3)
# print("ans =", ans)

# cnt1 = 10
# cnt2 = 10
# cnt3 = 10
# ans = 0

ans2 = ans
ans += max(cnt1 - 1, 0) + min(cnt2, cnt3)
if cnt2 != cnt3 and cnt1 > 0:
    ans += 1
# print(ans)

ans2 += min(cnt2, cnt3)
cnt2 -= min(cnt2, cnt3)
cnt3 -= min(cnt2, cnt3)
ans2 += min(max(cnt2, cnt3), cnt1)
cnt1 -= min(max(cnt2, cnt3), cnt1)
# ans2 += cnt1 // 2
ans2 += max(0, cnt1 - 1)
# print(ans2)

print(max(ans, ans2))

Submission status: Wrong Answer

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
from operator import mul

INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 組合せnCr
def combinations_count(n, r):
    if n < r:
        return 0
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

# ここから書き始める
n = int(input())
s = [input() for i in range(n)]

cnt1 = 0
cnt2 = 0
cnt3 = 0
ans = 0
for i in s:
    ans += i.count("AB")
    if i[0] == "B" and i[-1] == "A":
        cnt1 += 1
    elif i[0] == "B":
        cnt2 += 1
    elif i[-1] == "A":
        cnt3 += 1

# print("cnt1 =", cnt1)
# print("cnt2 =", cnt2)
# print("cnt3 =", cnt3)
# print("ans =", ans)

# cnt1 = 1
# cnt2 = 1
# cnt3 = 1
# ans = 0
ans2 = ans
ans += max(cnt1 - 1, 0) + min(cnt2, cnt3)
if cnt2 != cnt3 and cnt1 > 0:
    ans += 1
# print(ans)

ans2 += min(cnt2, cnt3)
cnt2 -= min(cnt2, cnt3)
cnt3 -= min(cnt2, cnt3)
ans2 += min(max(cnt2, cnt3), cnt1)
cnt1 -= min(max(cnt2, cnt3), cnt1)
ans2 += cnt1 // 2
# print(ans2)

print(max(ans, ans2))

Submission status: Wrong Answer

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
from operator import mul

INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 組合せnCr
def combinations_count(n, r):
    if n < r:
        return 0
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

# ここから書き始める
n = int(input())
s = [input() for i in range(n)]

cnt1 = 0
cnt2 = 0
cnt3 = 0
ans = 0
for i in s:
    ans += i.count("AB")
    if i[0] == "B" and i[-1] == "A":
        cnt1 += 1
    elif i[0] == "B":
        cnt2 += 1
    elif i[-1] == "A":
        cnt3 += 1
# print("cnt1 =", cnt1)
# print("cnt2 =", cnt2)
# print("cnt3 =", cnt3)
# print("ans =", ans)

ans += max(cnt1 - 1, 0) + min(cnt2, cnt3)
if cnt2 != cnt3 and cnt1 > 0:
    ans += 1
print(ans)
# ans += min(cnt2, cnt3)
# cnt2 -= min(cnt2, cnt3)
# cnt3 -= min(cnt2, cnt3)
# ans += min(max(cnt2, cnt3), cnt1)
# cnt1 -= min(max(cnt2, cnt3), cnt1)
# ans += cnt1 // 2
# print(ans)