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())
ans = 0
a, b, ab = 0, 0, 0
for _ in range(n):
    s = list(input())
    l = len(s)
    for i in range(l - 1):
        if s[i] == "A" and s[i + 1] == "B":
            ans += 1
    if s[0] == "B":
        b += 1
    if s[l - 1] == "A":
        a += 1
    if s[0] == "B" and s[l - 1] == "A":
        ab += 1
if a == b == ab:
    a -= 1
ans += min(n - 1, min(a, b))
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
li = ["A","B"]
L = []
for i in range(n):
    s = input()    #print(s)
    S = ""
    for j in range(len(s)):
        if s[j] in li:
            S += s[j]    #print(S)
    L.append(S)

L = [x for x in L if x]

ab = []
a = []
b = []
ba = []
for i in range(len(L)):
    if L[i][0] == "A" and L[i][-1] == "B":
        ab.append(L[i])
    elif L[i][0] == "A" and L[i][-1] == "A":
        a.append(L[i])
    elif L[i][0] == "B" and L[i][-1] == "B":
        b.append(L[i])
    elif L[i][0] == "B" and L[i][-1] == "A":
        ba.append(L[i])
#print(ab,a,b,ba)
ans = "".join(ab)
for i in range(min(len(a),len(ba))):
    ans +=a[i]+ba[i]

if b:
    ans +="B"
    b.pop()
if len(a) >= len(ba):
    d = len(a)-len(ba)
    if d > 0 and b:
        if d >= len(b):
            for i in range(len(b)):
                ans +=a[i] + b[i]
        elif d < len(b):
            for i in range(d):
                ans +=a[i] + b[i]
cnt = 0
for i in range(len(ans)-1):
    if ans[i] == "A" and ans[i+1] == "B":
        cnt  +=1
print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
li = ["A","B"]
L = []
for i in range(n):
    s = input()    #print(s)
    S = ""
    for j in range(len(s)):
        if s[j] in li:
            S += s[j]    #print(S)
    L.append(S)

L = [x for x in L if x]

ab = []
a = []
b = []
ba = []
for i in range(len(L)):
    if L[i][0] == "A" and L[i][-1] == "B":
        ab.append(L[i])
    elif L[i][0] == "A" and L[i][-1] == "A":
        a.append(L[i])
    if L[i][0] == "B" and L[i][-1] == "B":
        b.append(L[i])
    if L[i][0] == "B" and L[i][-1] == "A":
        ba.append(L[i])
#print(ab,a,b,ba)
ans = "".join(ab)
for i in range(min(len(a),len(ba))):
    ans +=a[i]+ba[i]

if b:
    ans +="B"
    b.pop()
if len(a) >= len(ba):
    d = len(a)-len(ba)
    if d > 0 and b:
        if d >= len(b):
            for i in range(len(b)):
                ans +=a[i] + b[i]
        elif d < len(b):
            for i in range(d):
                ans +=a[i] + b[i]
cnt = 0
for i in range(len(ans)-1):
    if ans[i] == "A" and ans[i+1] == "B":
        cnt  +=1
print(cnt)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def read_a_int(): return int(read())


def read_ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# https://atcoder.jp/contests/diverta2019/tasks/diverta2019_c

# B*A,*A,B*,*の4つに分類される。
# *に関しては事前に全部カウントしておけば良い
# B*A同士で作ったほうが有利(個数-1増える)
# *A,B*は 少ない方の個数増える
# 後者2つはコーナーケースに注意(つまり、B*Aがデータセットにある場合はさらに+1できる)(消化しきれない場合)

N = int(input())
base = 0
b_ = 0
_a = 0
b_a = 0
for _ in range(N):
    s = read()[:-1]
    if s.startswith('B') and s.endswith('A'):
        b_a += 1
    elif s.startswith('B'):
        b_ += 1
    elif s.endswith('A'):
        _a += 1
    base += s.count('AB')


print(base + b_a + min(b_, _a) + (-1 if b_ == _a and b_a > 0 else 0))
# print(base, b_a, b_, _a)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def read_a_int(): return int(read())


def read_ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# https://atcoder.jp/contests/diverta2019/tasks/diverta2019_c

# B*A,*A,B*,*の4つに分類される。
# *に関しては事前に全部カウントしておけば良い
# B*A同士で作ったほうが有利(個数-1増える)
# *A,B*は 少ない方の個数増える
# 後者2つはコーナーケースに注意(つまり、B*Aがデータセットにある場合はさらに+1できる)(消化しきれない場合)

N = int(input())
base = 0
b_ = 0
_a = 0
b_a = 0
for _ in range(N):
    s = read()[:-1]
    if s.startswith('B') and s.endswith('A'):
        b_a += 1
    elif s.startswith('B'):
        b_ += 1
    elif s.endswith('A'):
        _a += 1
    base += s.count('AB')

print(base + max(b_a - 1, 0) + min(b_, _a) +
      (1 if (b_ != _a) and b_a > 0 else 0))
# print(base, b_a, b_, _a)

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for i in range(n)]

ans = 0
a_cnt = 0
b_cnt = 0
for i in range(n):
    ans+=S[i].count('AB')
    if S[i][-1]=='A':
        a_cnt+=1
    if S[i][0]=='B':
        b_cnt+=1

print(ans+min(a_cnt,b_cnt,n-1))

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for i in range(n)]

ans = 0
a_cnt = 0
b_cnt = 0
for i in range(n):
    ans+=S[i].count('AB')
    if S[i][-1]=='A':
        a_cnt+=1
    if S[i][0]=='B':
        b_cnt+=1

print(ans+min(a_cnt,b_cnt))

Submission status: Wrong Answer

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n = I()
B = 0
A = 0
ans = 0
for i in range(n):
    s = input()
    ans += s.count('AB')
    if len(s)!=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 = 0#末尾がA
B = 0#先頭がB
BA = 0#先頭がB かつ 末尾がA
AB = 0#ABの数

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

if min(A,B) > 0:
    ans += BA + 1
    A -= 1
    B -= 1
    ans += min(A,B)
else:
    ans += BA + min(1, max(A,B)) -1
print(ans)
    
#if BA > max(A,B) - min(A,B):
#    ans += (BA - (max(A,B) - min(A,B))) / 2
#print(A,B,BA,AB)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = 0#末尾がA
B = 0#先頭がB
BA = 0#先頭がB かつ 末尾がA
AB = 0#ABの数

for i in range(N):
    s = input()
    AB += s.count("AB")
    if s[0] == "B":
        B += 1
    if s[-1] == "A":
        A += 1
    if s[0] == "B" and s[-1] == "A":
        BA += 1
        B -= 1
        A -= 1
ans = 0
ans += AB
ans += min(A,B)
if BA == 0:
    print(ans)
    exit()
else:
    ans += BA + min(1, max(A,B) - min(A,B)) - 1
    print(ans)
#if BA > max(A,B) - min(A,B):
#    ans += (BA - (max(A,B) - min(A,B))) / 2
#print(A,B,BA,AB)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = 0#末尾がA
B = 0#先頭がB
BA = 0#先頭がB かつ 末尾がA
AB = 0#ABの数

for i in range(N):
    s = input()
    AB += s.count("AB")
    if s[0] == "B":
        B += 1
    if s[-1] == "A":
        A += 1
    if s[0] == "B" and s[-1] == "A":
        BA += 1
        B -= 1
        A -= 1
ans = 0
ans += AB
ans += min(A,B)
ans += BA + max(min(1, max(A,B) - min(A,B)) - 1, 0)
#if BA > max(A,B) - min(A,B):
#    ans += (BA - (max(A,B) - min(A,B))) / 2
#print(A,B,BA,AB)
print(ans)

Submission status: Wrong Answer

Solution code:
n,*a=open(0).read().split()
ba=xa=bx=ans=0
for i in a:
    if i[0]=="B" and i[-1]=="A":
        ba+=1
    elif i[0]=="B":
        bx+=1
    elif i[-1]=="A":
        xa+=1
    ans+=i.count("AB")    
if ba==0:
    print(ans+min(xa,bx))
else:
    if xa==bx:
        print(ans+ba-1)
    else:    
        print(ans+min(xa,bx)+ba)

Submission status: Wrong Answer

Solution code:
n,*a=open(0).read().split()
ba=xa=bx=ans=0
for i in a:
    if i[0]=="B" and i[-1]=="A":
        ba+=1
    elif i[0]=="B":
        bx+=1
    elif i[-1]=="A":
        xa+=1
    ans+=i.count("AB")    
print(ans+min(xa,bx)+max(0,ba-1)+1*(ba>0 and xa-bx!=0))

Submission status: Wrong Answer

Solution code:
N=int(input())
s = [input() for _ in range(N)]
t = [s[i].count("AB") for i in range(N)]
u = sum([1 if s[i][-1] == "A" else 0 for i in range(N)])
v = sum([1 if s[i][0] == "B" else 0 for i in range(N)])
w = sum([1 if s[i][0] == "B" and s[i][-1] == "A" else 0 for i in range(N)])

#print(t)
#print(u,v,w)

maxi=max(u,v)
mini=min(u,v)
#print(maxi,mini,w)

maxi -= w
diff = maxi-mini
print(maxi,mini,w)

ans = min(mini,maxi) + min(diff,w) + sum(t)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
cnt_ba = 0
cnt_a = 0
cnt_b = 0
for _ in range(n):
    s = str(input())
    ans += s.count('AB')
    if s[-1] == 'A' and s[0] == 'B':
        cnt_ba += 1
    elif s[-1] == 'A':
        cnt_a += 1
    elif s[0] == 'B':
        cnt_b += 1
if n >= 2:
    if cnt_a == cnt_b == 0:
        ans += cnt_ba - 1
    else:
        ans += min(cnt_a, cnt_b) + cnt_ba
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
cnt_ba = 0
cnt_a = 0
cnt_b = 0
for _ in range(n):
    s = str(input())
    ans += s.count('AB')
    if s[-1] == 'A' and s[0] == 'B':
        cnt_ba += 1
    elif s[-1] == 'A':
        cnt_a += 1
    elif s[0] == 'B':
        cnt_b += 1
if n >= 2:
    ans += min(cnt_a, cnt_b) + cnt_ba
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
last_a = 0
first_b = 0
cnt = 0
both = 0
for i in range(n):
    ss = input()
    s.append(ss)
    if ss[0] == 'B':
        first_b += 1
    if ss[-1] == 'A':
        last_a += 1
    if ss[0] == 'B' and ss[-1] == 'A':
        both += 1
        last_a -= 1
        first_b -= 1

    for j in range(len(ss)-1):
        if ss[j] == 'A' and ss[j+1] == 'B':
            cnt += 1

tmp = both
if both > 1:
    tmp = both - 1
print(min(last_a,first_b) + cnt + tmp)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
last_a = 0
first_b = 0
cnt = 0
both = 0
for i in range(n):
    ss = input()
    s.append(ss)
    if ss[0] == 'B':
        first_b += 1
    if ss[-1] == 'A':
        last_a += 1
    if ss[0] == 'B' and ss[-1] == 'A':
        both += 1

    for j in range(len(ss)-1):
        if ss[j] == 'A' and ss[j+1] == 'B':
            cnt += 1
if both == last_a == first_b:
    print(min(last_a,first_b) + cnt - 1)
print(min(last_a,first_b) + cnt )

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
last_a = 0
first_b = 0
cnt = 0
for i in range(n):
    ss = input()
    s.append(ss)
    if ss[0] == 'B':
        first_b += 1
    if ss[-1] == 'A':
        last_a += 1

    for j in range(len(ss)-1):
        if ss[j] == 'A' and ss[j+1] == 'B':
            cnt += 1

print(min(last_a,first_b) + cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
res = 0
numa = numb = numboth = 0
for _ in range(n):
    s = input()
    res += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        numboth += 1
    elif s[0] == "B":
        numb += 1
    elif s[-1] == "A":
        numa += 1

#print(numboth, numa, numb)
#print(res)

if numa != 0 or numb != 0:
    res += numboth
else:
    if numboth != 0:
        res += numboth - 1

res += min(numa, numb)

Submission status: Wrong Answer

Solution code:
n = int(input())
res = 0
numa = numb = numboth = 0
for _ in range(n):
    s = input()
    res += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        numboth += 1
    elif s[0] == "B":
        numb += 1
    elif s[-1] == "A":
        numa += 1

#print(numboth, numa, numb)
#print(res)

if numa != 0 or numb != 0:
    res += numboth

res += min(numa, numb)

print(res)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
a = 0
b = 0
ba = 0
for i in range(n):
    s = input()
    ans += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            ba += 1
        else:
            b += 1
    elif s[-1] == "A":
        a += 1
if a >= 1 and b >= 1:
    print(ans+ba+1+min(a-1,b-1))
elif a >= 1 or b >= 1:
    print(ans+ba)
else:
    print(ans+ba-1)

Submission status: Wrong Answer

Solution code:
n = int(input())
slist = []
ans = 0
startB, endA = 0, 0
for _ in range(n):
    s = list(input())
    for j in range(len(s) - 1):
        if ("".join(s[j:j + 2]) == "AB"):
            ans += 1
    startB += 1 if s[0] == "B" else 0
    endA += 1 if s[len(s) - 1] == "A" else 0

if startB == endA:
    startB -= 1

print(ans+min(startB, endA))

Submission status: Wrong Answer

Solution code:
n = int(input())
slist = []
ans = 0
startB, endA = 0, 0
for _ in range(n):
    s = list(input())
    for j in range(len(s) - 1):
        if ("".join(s[j:j + 2]) == "AB"):
            ans += 1
    startB += 1 if s[0] == "B" else 0
    endA += 1 if s[len(s) - 1] == "A" else 0

print(ans+min(startB, endA))

Submission status: Wrong Answer

Solution code:
N=int(input())
b,ba,a=0,0,0
ans=0
for i in range(N):
    s=input()
    for i in range(len(s)-1):
        if s[i:i+2]=='AB':
            ans+=1
    if s[0]=='B' and s[-1]=='A':
        ba+=1
    elif s[-1]=='A':
        a+=1
    elif s[0]=='B':
        b+=1
if b==0 and a==0:
    print(ans+min(ba-1,0))
else:
    print(ans+ba+min(a,b))

Submission status: Wrong Answer

Solution code:
N=int(input())
b,ba,a=0,0,0
ans=0
for i in range(N):
    s=input()
    for i in range(len(s)-1):
        if s[i:i+2]=='AB':
            ans+=1
    if s[0]=='B' and s[-1]=='A':
        ba+=1
    elif s[-1]=='A':
        a+=1
    elif s[0]=='B':
        b+=1
if b==a==0:
    print(ans+min(ba-1,0))
else:
    print(ans+ba+min(a,b))

Submission status: Wrong Answer

Solution code:
N=int(input())
b,ba,a=0,0,0
ans=0
for i in range(N):
    s=input()
    for i in range(len(s)-1):
        if s[i:i+2]=='AB':
            ans+=1
    if s[0]=='B' and s[-1]=='A':
        ba+=1
    elif s[-1]=='A':
        a+=1
    elif s[0]=='B':
        b+=1
m=''
t=True
while a>0 and b>0 and ba>0:
    m+='XABXABX'
    a-=1;b-=1;ba-=1
while a>0 and b>0:
    m+='XABX'
    a-=1;b-=1
if a>0:
    m+='XA'
while ba>0:
    m+='BXA'
    ba-=1
    
for i in range(len(m)-1):
    if m[i:i+2]=='AB':
        ans+=1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
for i in range(n):
    s.append(input())

cnt_end_a = 0
cnt_bgn_b = 0
cnt_end_a_bgn_b = 0

ans = 0
for i in range(n):
    if s[i][0] == 'B':
        if s[i][len(s[i])-1] == 'A':
            cnt_end_a_bgn_b += 1
        else:
            cnt_bgn_b += 1
    elif s[i][len(s[i])-1] == 'A':
        cnt_end_a += 1
    for j in range(len(s[i])-1):
        if s[i][j] == 'A' and s[i][j+1] == 'B':
            ans += 1

#print(cnt_end_a, cnt_bgn_b, cnt_end_a_bgn_b)

if cnt_end_a_bgn_b == 0:
    ans += min(cnt_bgn_b, cnt_end_a)
elif cnt_end_a == 0 and cnt_bgn_b == 0:
    ans += cnt_end_a_bgn_b - 1
elif cnt_end_a == 0:
    ans += cnt_end_a_bgn_b
elif cnt_bgn_b == 0:
    ans += cnt_end_a_bgn_b
else:
    ans += cnt_end_a_bgn_b + min(max(cnt_bgn_b, cnt_end_a)-1, min(cnt_bgn_b, cnt_end_a))
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())

ans = 0
last_a = 0
first_b = 0

for i in range(n):
    s = input()
    ans += s.count("AB")
    if s[-1] == "A":
        last_a += 1
    if s[0] == "B":
        first_b += 1

print(ans + min(last_a, first_b))

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
from fractions import gcd
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

from itertools import permutations
from math import factorial, hypot

#############
# Main Code #
#############

N = getN()
cnt = 0
last_a = 0
first_b = 0
double = 0
for i in range(N):
    s = input()
    for j in range(len(s) - 1):
        if s[j] == 'A' and s[j + 1] == 'B':
            cnt += 1
    if s[0] == 'B' and s[-1] == 'A':
        double += 1
    elif s[0] == 'B':
        first_b += 1
    elif s[-1] == 'A':
        last_a += 1
opt1 = 0
opt2 = 0
if first_b >= 1 and last_a >= 1:
    if double >= 1:
        opt1 = double + 1
        opt2 = min(first_b - 1, last_a - 1)
    else:
        opt1 = min(first_b, last_a)
else:
    if first_b == 0 and last_a == 0:
        opt1 = min(double - 1, 0)
    else:
        opt1 = double
print(cnt + opt1 + opt2)

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
from fractions import gcd
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

from itertools import permutations
from math import factorial, hypot

#############
# Main Code #
#############

N = getN()
cnt = 0
last_a = 0
first_b = 0
double = 0
for i in range(N):
    s = input()
    for j in range(len(s) - 1):
        if s[j] == 'A' and s[j + 1] == 'B':
            cnt += 1
    if s[0] == 'B' and s[-1] == 'A':
        double += 1
    elif s[0] == 'B':
        first_b += 1
    elif s[-1] == 'A':
        last_a += 1
opt1 = 0
opt2 = 0
if first_b >= 1 and last_a >= 1:
    if double >= 1:
        opt1 = double + 1
        opt2 = min(first_b - 1, last_a - 1)
    else:
        opt1 = min(first_b, last_a)
else:
    opt1 = double
print(cnt + opt1 + opt2)

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
from fractions import gcd
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

from itertools import permutations
from math import factorial, hypot

#############
# Main Code #
#############

N = getN()
cnt = 0
last_a = 0
first_b = 0
double = 0
for i in range(N):
    s = input()
    for j in range(len(s) - 1):
        if s[j] == 'A' and s[j + 1] == 'B':
            cnt += 1
    if s[0] == 'B' and s[-1] == 'A':
        double += 1
    elif s[0] == 'B':
        first_b += 1
    elif s[-1] == 'A':
        last_a += 1
opt1 = 0
opt2 = 0
if first_b >= 1 and last_a >= 1:
    opt1 = double + 1
    opt2 = min(first_b - 1, last_a - 1)
else:
    opt1 = double
print(cnt + opt1 + opt2)

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
from fractions import gcd
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

from itertools import permutations
from math import factorial, hypot

#############
# Main Code #
#############

N = getN()
cnt = 0
last_a = 0
first_b = 0
for i in range(N):
    s = input()
    for j in range(len(s) - 1):
        if s[j] == 'A' and s[j + 1] == 'B':
            cnt += 1
    if s[0] == 'B':
        first_b += 1
    if s[-1] == 'A':
        last_a += 1
opt = min(N - 1, first_b, last_a)
cnt += opt
print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())

ab = 0
x = 0
y = 0
z = 0

for _ in range(N):
    s = input()
    ab += s.count("AB")
    x += (s[-1] == "A")
    y += (s[0] == "B")
    z += (s[-1] == "A" and s[0] == "B")

if x or y:
    print(ab + min(x+z, y+z))
else:
    print(ab + z-1)

Submission status: Wrong Answer

Solution code:
N = int(input())

a = 0
b = 0
ab = 0

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

print(ab + min(N-1, a, b))

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[]
cnt=Alist=Blist=0
key=False
for i in range(N):
    s=input()
    cnt+=s.count("AB")
    S=list(s)
    if S[0] == "B":
        Blist+=1
    if S[-1] == "A":
        Alist+=1
    if (S[0] == "B" and S[-1] != "A") or (S[0] != "B" and S[-1] == "A"):
        key = True

cnt += min(Alist,Blist)
if key:
    print(cnt)
elif cnt==0:
    print(cnt)
else:
    print(cnt-1)

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[]
cnt=Alist=Blist=0
key=False
for i in range(N):
    s=input()
    cnt+=s.count("AB")
    S=list(s)
    if S[0] == "B":
        Blist+=1
    if S[-1] == "A":
        Alist+=1
    if (S[0] == "B" and S[-1] != "A") or (S[0] != "B" and S[-1] == "A"):
        key = True

cnt += min(Alist,Blist)
if key:
    print(cnt)
else:
    print(cnt-1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6) #再帰関数の上限
import math
from copy import copy, deepcopy
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque 
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする


def input(): return sys.stdin.readline()[:-1]
def printl(li): print(*li, sep="\n")
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N=len(v)
    size=len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def main():
    mod = 10**9+7
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    count=0

    ab=0
    a=0
    b=0
    for i in range(N):
        s=input()
        ls=len(s)
        for j in range(ls-1):
            if s[j:j+2]=='AB':
                count+=1
        if s[0]=='B' and s[-1]=='A':
            ab+=1
        elif s[-1]=='A':
            a+=1
        elif s[0]=='B':
            b+=1
    if a==0 and b==0:
        print(max(ab-1,0))
        exit()
    ans=min(a,b)+count
    ret=abs(a-b)
    if ret<=ab:
        ans+=ab
    else:
        ans+=ab
    print(ans)
    

    


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6) #再帰関数の上限
import math
from copy import copy, deepcopy
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque 
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする


def input(): return sys.stdin.readline()[:-1]
def printl(li): print(*li, sep="\n")
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N=len(v)
    size=len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def main():
    mod = 10**9+7
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    count=0

    ab=0
    a=0
    b=0
    for i in range(N):
        s=input()
        ls=len(s)
        for j in range(ls-1):
            if s[j:j+2]=='AB':
                count+=1
        if s[0]=='B' and s[-1]=='A':
            ab+=1
        elif s[-1]=='A':
            a+=1
        elif s[0]=='B':
            b+=1
    ans=min(a,b)+count
    ret=abs(a-b)
    if ret<=ab:
        ans+=ab
    else:
        ans+=ab
    print(ans)
    

    


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6) #再帰関数の上限
import math
from copy import copy, deepcopy
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque 
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする


def input(): return sys.stdin.readline()[:-1]
def printl(li): print(*li, sep="\n")
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N=len(v)
    size=len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def main():
    mod = 10**9+7
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    count=0

    ab=0
    a=0
    b=0
    for i in range(N):
        s=input()
        ls=len(s)
        for j in range(ls-1):
            if s[j:j+2]=='AB':
                count+=1
        if s[0]=='B' and s[-1]=='A':
            ab+=1
        elif s[-1]=='A':
            a+=1
        elif s[0]=='B':
            b+=1
    ans=min(a,b)+count
    ret=max(a,b)
    if ret<=ab:
        ans+=ab
    else:
        ans+=ab
    print(ans)
    

    


if __name__ == "__main__":
    main()