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())
s=[input() for i in range(n)]
lastA=0
firstB=0
lastAandfirstB=0
ABs=0
for si in s:
    ABs+=si.count("AB")
    firstB+=(si[0]=="B")
    lastA+=(si[-1]=="A")
    lastAandfirstB+=(si[0]=="B")*(si[-1]=="A")

can=min(firstB,lastA)
if lastAandfirstB==1 and firstB==1 and lastA==1:
    print(ABs)
    exit()
if can==n:
    can=n-1
print(can+ABs)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[input() for i in range(n)]
lastA=0
firstB=0
lastAandfirstB=0
ABs=0
for si in s:
    ABs+=si.count("AB")
    firstB+=(si[0]=="B")
    lastA+=(si[-1]=="A")
    lastAandfirstB+=(si[0]=="B")*(si[-1]=="A")

can=min(firstB,lastA)
if can==lastAandfirstB:
    print(ABs)
    exit()
if can==n:
    can=n-1
print(can+ABs)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[input() for i in range(n)]
lastA=0
firstB=0
ABs=0
for si in s:
    ABs+=si.count("AB")
    firstB+=(si[0]=="B")
    lastA+=(si[-1]=="A")

can=min(firstB,lastA)
if can==n:
    can=n-1
print(can+ABs)

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for _ in range(n)]
XA = 0
BA = 0
BX = 0
cnt = 0
for s in S:
    if 'AB' in s:
        cnt+=1
    if s[0]!='B' and s[len(s)-1]=='A':
        XA+=1
    elif s[0]=='B' and s[len(s)-1]=='A':
        BA+=1
    elif s[0]=='B' and s[len(s)-1]!='A':
        BX+=1
if BA==0:
    cnt+=min(XA,BX)
else:
    if XA+BX>0:
        cnt+=min(XA,BX)+BA
    else:
        cnt+=BA-1
print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for _ in range(n)]
XA = 0
BA = 0
BX = 0
cnt = 0
for s in S:
    if 'AB' in s:
        cnt+=1
    if s[0]!='B' and s[len(s)-1]=='A':
        XA+=1
    elif s[0]=='B' and s[len(s)-1]=='A':
        BA+=1
    elif s[0]=='B' and s[len(s)-1]!='A':
        BX+=1
if BA==0:
    cnt+=min(XA,BX)
else:
    if XA+BX>0:
        cnt+=min(XA,BX)+BA
print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for _ in range(n)]
XA = 0
BA = 0
BX = 0
cnt = 0
for s in S:
    if 'AB' in s:
        cnt+=1
    if s[0]!='B' and s[len(s)-1]=='A':
        XA+=1
    elif s[0]=='B' and s[len(s)-1]=='A':
        BA+=1
    elif s[0]=='B' and s[len(s)-1]!='A':
        BX+=1
if XA>0:
    cnt+=BA
    cnt+=min(XA,BX)
else:
    cnt+=min(BA,BX)
print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
r = 0
a = 0
b = 0
for _i in range(n):
    s = input()
    r += s.count("AB")
    B = 0
    A = 0
    if s[-1]=="A":
        if b > 0:
            b -= 1
            r += 1
        else:
            A += 1
    if s[0]=="B":
        if a > 0:
            a -= 1
            r += 1
        else:
            B += 1
    a += A
    b += B


print(r)

Submission status: Wrong Answer

Solution code:
n = int(input())
r = 0
a = 0
b = 0
for _i in range(n):
    s = input()
    r += s.count("AB")
    B = 0
    if s[0]=="B":
        if a > 0:
            a -= 1
            r += 1
        else:
            B += 1
    if s[-1]=="A":
        if b > 0:
            b -= 1
            r += 1
        else:
            a += 1
    b += B


print(r)

Submission status: Wrong Answer

Solution code:
n = int(input())
r = 0
a = 0
b = 0
for _i in range(n):
    s = input()
    r += s.count("AB")
    h = True
    if s[0]=="B":
        if b > 0:
            b -= 1
            r += 1
        else:
            a += 1
            h = False
    if s[len(s)-1]=="A":
        if h:
            if a > 0:
                a -= 1
                r += 1
            else:
                b += 1
        else:
            if a > 1:
                a -= 1
                r += 1
            else:
                b += 1
print(r)

Submission status: Wrong Answer

Solution code:
n = int(input())
r = 0
a = 0
b = 0
for _i in range(n):
    s = input()
    r += s.count("AB")
    h = True
    if s[0]=="B":
        if b > 0:
            b -= 1
            r += 1
        else:
            a += 1
            h = False
    if s[-1]=="A":
        if h:
            if a > 0:
                a -= 1
                r += 1
            else:
                b += 1
        else:
            if a > 1:
                a -= 1
                r += 1
            else:
                b += 1
print(r)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    
    N=int(input())
    x=0
    y=0
    z=0
    cnt=0
    for i in range(N):
        s=str(input())
        if s[0]=='B' and s[-1]=='A':
            x+=1
        if s[0]=='B' and s[-1]!='A':
            y+=1
        if s[0]!='B' and s[-1]=='A':
            z+=1

        
        for j in range(len(s)-1):
            if s[j:j+2]=='AB':
                cnt+=1
    if x==0:
        print(cnt+min(y,z))
    elif y!=z: print(cnt+(x-1)+min(y,z)+1)
    else: print(cnt+(x-1)+min(y,z))    
        

    
resolve()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
for _ in range(n):
    s.append(input())
a = 0
b = 0
ans = 0
same = 0
for i in s:
    flg = False
    if i[0]=='B':
        flg = True
        b += 1
    if i[-1]=='A':
        a += 1
        if flg:
            same += 1
    for j in range(len(i)-1):
        if i[j:j+2]=='AB':
            ans += 1
ans += min(a, b)
if a == b == same:
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    
    N=int(input())
    cnt=0
    cntB=0
    cntA=0

    for i in range(N):
        s=str(input())
        if s[0]=='B':
            cntB+=1
        if s[-1]=='A':
            cntA+=1
        
        for j in range(len(s)-1):
            if s[j:j+2]=='AB':
                cnt+=1
        
    print(cnt+min(cntA,cntB))
        

    
resolve()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
for _ in range(n):
    s.append(input())
a = 0
b = 0
ans = 0
same = 0
for i in s:
    flg = False
    if i[0]=='B':
        flg = True
        b += 1
    if i[-1]=='A':
        a += 1
        if flg:
            same += 1
    for j in range(len(i)-1):
        if i[j:j+2]=='AB':
            ans += 1
ans += min(n-1, a, b)
if a == b == same:
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
for _ in range(n):
    s.append(input())
a = 0
b = 0
ans = 0
same = 0
for i in s:
    flg = False
    if i[0]=='B':
        flg = True
        b += 1
    if i[-1]=='A':
        a += 1
        if flg:
            same += 1
    for j in range(len(i)-1):
        if i[j:j+2]=='AB':
            ans += 1
ans += min(n-1, a, b)
if min(a, b) == same:
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
for _ in range(n):
    s.append(input())
a = 0
b = 0
ans = 0
same = 0
for i in s:
    flg = False
    if i[0]=='B':
        flg = True
        b += 1
    if i[-1]=='A':
        a += 1
        if flg:
            same += 1
    for j in range(len(i)-1):
        if i[j:j+2]=='AB':
            ans += 1
ans += min(n-1, a, b)
if ans == same:
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
for _ in range(n):
    s.append(input())
a = 0
b = 0
ans = 0
for i in s:
    if i[0]=='B':
        b += 1
    if i[-1]=='A':
        a += 1
    for j in range(len(i)-1):
        if i[j:j+2]=='AB':
            ans += 1
ans += min(n-1, a, b)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import Counter

DEBUG = False

N = int(input())
S = []
patterns = []
ans = 0
for _ in range(N):
    s = input()
    # S.append(s)
    ans += s.count("AB")
    # 3進数表記 -> 1bit目: 先頭の文字, 2bit目: 末尾の文字
    # A = 0, B = 1, O:other = 2
    # A...A: 0, A...B: 1, A...O: 2
    # B...A: 3, B...B: 4, B...O: 5
    # O...A: 6, O...B: 7, O...O: 8
    pattern = ""
    pattern += "2" if (s[0] != "A"  and s[0] != "B") else "1" if s[0] == "B" else "0"
    pattern += "2" if (s[-1] != "A" and s[-1] != "B") else "1" if s[-1] == "B" else "0"
    patterns.append(int(pattern, 3))
    if DEBUG:
        print("s: {}, pattern: {}".format(s, pattern))

if DEBUG:
    print("patterns: {}".format(patterns))
    print("ans: {}".format(ans))

counter = Counter(patterns)
if DEBUG:
    print("counter: {}".format(counter))

ans += counter[3] - 1 if counter[3] else 0
if DEBUG:
    print("ans: {}".format(ans))


num_tail_A = counter[0] + counter[6]
num_tail_A += 1 if counter[3] else 0
num_head_B = counter[4] + counter[5]
num_head_B += 1 if counter[3] else 0
if DEBUG:
    print("num_tail_A: {}, num_head_B: {}".format(num_tail_A, num_head_B))

ans += min(num_tail_A, num_head_B)

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]

cnt = 0
end_a = 0
sta_b = 0
a_b = 0
for s in S:
    cnt += s.count('AB')
    if s[-1]=='A' and s[0]=='B':
        a_b += 1
    elif s[-1]=='A':
        end_a += 1
    elif s[0]=='B':
        sta_b += 1
if a_b>=1:
    cnt += a_b-1
if end_a==sta_b:
    cnt += end_a
else:
    cnt += min(end_a, sta_b)
    if a_b>=1:
        cnt += 1

print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]

cnt = 0
end_a = 0
sta_b = 0
a_b = 0
for s in S:
    cnt += s.count('AB')
    if s[-1]=='A' and s[0]=='B':
        a_b += 1
    elif s[-1]=='A':
        end_a += 1
    elif s[0]=='B':
        sta_b += 1

a_b = [a_b, a_b]
if a_b[0]>=end_a:
    cnt += end_a
    a_b[0] -= end_a
    end_a = 0
else:
    cnt += a_b[0]
    end_a -= a_b[0]
    a_b[0] = 0
if a_b[1]>=sta_b:
    cnt += sta_b
    a_b[1] -= sta_b
    sta_b = 0
else:
    cnt += a_b[1]
    sta_b -= a_b[1]
    a_b[1] = 0
cnt += min(end_a, sta_b)
cnt += min(a_b)
print(cnt)

Submission status: Wrong Answer

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

fi = 0
sec = 0
thi = 0
forth = 0

for i in range(n):
    cnt =  s[i].count("AB")
    if cnt>=1:
        fi+=cnt

    syo = s[i][0]
    saigo = s[i][-1]

    if syo =="B" and saigo == "A":
        sec+=1
    elif syo == "B":
        thi+=1
    elif saigo=="A":
        forth+=1

su=0
if sec>=1:
    su += sec-1

su+=fi

if thi!=forth:
    su+=min(thi,forth)+1
else:
    su+=thi

#print(fi,sec,thi,forth)
print(su)

Submission status: Wrong Answer

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

fi = 0
sec = 0
thi = 0
forth = 0

for i in range(n):
    cnt =  s[i].count("AB")
    if cnt>=1:
        fi+=cnt

    syo = s[i][0]
    saigo = s[i][-1]

    if syo =="B" and saigo == "A":
        sec+=1
    elif syo == "B":
        thi+=1
    elif saigo=="A":
        forth+=1

su=0
if sec>=1:
    su += sec-1

su+=fi

if thi!=forth:
    su+=min(thi,forth)+1
else:
    su+=thi

print(fi,sec,thi,forth)
print(su)

Submission status: Wrong Answer

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

fi = 0
sec = 0
thi = 0
forth = 0

for i in range(n):
    cnt =  s[i].count("AB")
    if cnt>=1:
        fi+=1

    syo = s[i][0]
    saigo = s[i][-1]

    if syo =="B" and saigo == "A":
        sec+=1
    elif syo == "B":
        thi+=1
    elif saigo=="A":
        forth+=1

su=0
if sec>=1:
    su += sec-1

su+=fi

if thi!=forth:
    su+=min(thi,forth)+1
else:
    su+=thi

print(su)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]

cnt = sum(map(lambda x: x.count('AB'), S))
B_A = len(list(filter(lambda x: x[0] == 'B' and x[-1] == 'A', S)))
B__ = len(list(filter(lambda x: x[0] == 'B' and x[-1] != 'A', S)))
__A = len(list(filter(lambda x: x[0] != 'B' and x[-1] == 'A', S)))

if B__ == __A:
    print(cnt + B__ + B_A // 2)
else:
    s = min(B__, __A)
    t = abs(B__ - __A)
    print(cnt + s + B_A)

Submission status: Wrong Answer

Solution code:
from collections import Counter

DEBUG = False

N = int(input())
S = []
patterns = []
ans = 0
for _ in range(N):
    s = input()
    # S.append(s)
    if "AB" in s:
        ans += 1
    # 3進数表記 -> 1bit目: 先頭の文字, 2bit目: 末尾の文字
    # A = 0, B = 1, O:other = 2
    # A...A: 0, A...B: 1, A...O: 2
    # B...A: 3, B...B: 4, B...O: 5
    # O...A: 6, O...B: 7, O...O: 8
    pattern = ""
    pattern += "2" if (s[0] != "A"  and s[0] != "B") else "1" if s[0] == "B" else "0"
    pattern += "2" if (s[-1] != "A" and s[-1] != "B") else "1" if s[-1] == "B" else "0"
    patterns.append(int(pattern, 3))
    if DEBUG:
        print("s: {}, pattern: {}".format(s, pattern))

if DEBUG:
    print("patterns: {}".format(patterns))
    print("ans: {}".format(ans))

counter = Counter(patterns)
if DEBUG:
    print("counter: {}".format(counter))

ans += counter[3] - 1 if counter[3] else 0
if DEBUG:
    print("ans: {}".format(ans))


num_tail_A = counter[0] + counter[6]
num_tail_A += 1 if counter[3] else 0
num_head_B = counter[4] + counter[5]
num_head_B += 1 if counter[3] else 0
if DEBUG:
    print("num_tail_A: {}, num_head_B: {}".format(num_tail_A, num_head_B))

ans += min(num_tail_A, num_head_B)

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

ends_with_A = 0
starts_with_B = 0
both = 0

count = 0

for _ in range(N):
  s = input()
  count += s.count('AB')
  if s.endswith('A') and s.startswith('B'):
    both += 1
  elif s.endswith('A'):
    ends_with_A += 1
  elif s.startswith('B'):
    starts_with_B += 1

# 結合した文字が AXXXXXX or XXXXXXXB となるとき     
if abs(ends_with_A - starts_with_B) > 0:
  print(count + both + min(ends_with_A, starts_with_B))
else:  
  print(
    max(
      count + both + min(ends_with_A, starts_with_B) - 1,
      0
    )
  )

Submission status: Wrong Answer

Solution code:
N = int(input())

ends_with_A = 0
starts_with_B = 0
both = 0

count = 0

for _ in range(N):
  s = input()
  count += s.count('AB')
  if s.endswith('A') and s.startswith('B'):
    both += 1
  elif s.endswith('A'):
    ends_with_A += 1
  elif s.startswith('B'):
    starts_with_B += 1

# 結合した文字が AXXXXXX or XXXXXXXB となるとき     
if ends_with_A != starts_with_B:
  print(count + both + min(ends_with_A, starts_with_B))
else:  
  print(
    max(
      count + both + min(ends_with_A, starts_with_B) - 1,
      0
    )
  )

Submission status: Wrong Answer

Solution code:
N = int(input())

ends_with_A = 0
starts_with_B = 0
both = 0

count = 0

for _ in range(N):
  s = input()
  count += s.count('AB')
  if s.endswith('A') and s.startswith('B'):
    both += 1
  elif s.endswith('A'):
    ends_with_A += 1
  elif s.startswith('B'):
    starts_with_B += 1

if ends_with_A or starts_with_B:
  print(count + both + min(ends_with_A, starts_with_B))
else:  
  print(
    max(
      count + both + min(ends_with_A, starts_with_B) - 1,
      0
    )
  )

Submission status: Wrong Answer

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

a = 0
b = 0
ans = 0
flag = False
for s in S:
    ans += s.count('AB')
    if s[0] == 'B':
        b += 1
    if s[-1] == 'A':
        a += 1
    if s[0] == 'B' and s[-1] == 'A':
        flag = True

if flag and a == 1 and b == 1:
    pass
else:
    ans += min(a, b)
print(ans)

Submission status: Wrong Answer

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

a = 0
b = 0
ans = 0
for s in S:
    ans += s.count('AB')
    if s[0] == 'B':
        b += 1
    if s[-1] == 'A':
        a += 1
ans += min(a, b)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def diverta19_c():
    _ = int(readline())
    S = [ln.strip().decode('UTF-8') for ln in read().split()]

    # _AB_ , B_A , B_ , _A の個数をそれぞれ数える
    inner, st, ed, sted = 0, 0, 0, 0
    for si in S:
        inner += si.count('AB')
        if si[0] == 'B' and si[-1] == 'A': sted += 1
        elif si[0] == 'B': st += 1
        elif si[-1] == 'A': ed += 1

    ans = inner  # これは確定
    ans += min(st, ed)  # ペア作る律速は少ないほう
    if sted > 0: ans += (sted - 1)  # x個でx-1組のABができる
    if sted > 0 and st != ed: ans += 1  # ペアなれなかったやつを合体できる場合
    print(ans)

diverta19_c()

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

sys.setrecursionlimit(10 ** 7)

ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

from collections import defaultdict

n = ni()
s = nsn(n)

cnt = 0
dcnt = 0
dic = defaultdict(int)
for i in range(n):
    for j in range(len(s[i]) - 1):
        if s[i][j] == 'A' and s[i][j + 1] == 'B':
            cnt += 1
    dic['A'] += (s[i][-1] == 'A')
    dic['B'] += (s[i][0] == 'B')
    dcnt += s[i][-1] == 'A' and s[i][0] == 'B'

ans = min(dic['A'], dic['B'])
if max(dic['A'], dic['B']) == dcnt:
    print(ans - 1 + cnt)
else:
    print(ans + cnt)

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

sys.setrecursionlimit(10 ** 7)

ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

from collections import defaultdict

n = ni()
s = nsn(n)

cnt = 0
dic = defaultdict(int)
for i in range(n):
    for j in range(len(s[i]) - 1):
        if s[i][j] == 'A' and s[i][j + 1] == 'B':
            cnt += 1
    dic['A'] += (s[i][-1] == 'A')
    dic['B'] += (s[i][0] == 'B')

ans = min(dic['A'], dic['B'])
if ans == n:
    print(ans - 1 + cnt)
else:
    print(ans + cnt)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n=ii()
backa=0
frontb=0
backafrontb=0
ans=0
for i in range(n):
    s=list(ss())
    for j in range(len(s)-1):
        if s[j]+s[j+1]=="AB":
            ans+=1
    if s[0]=="B" and s[-1]=="A":
        backafrontb+=1
    elif s[0]=="B":
        frontb+=1
    elif s[-1]=="A":
        backa+=1
#print(backa,frontb,backafrontb,ans)

unit=0
if backa>=frontb:
    unit+=backa-frontb
    ans+=frontb
else:
    unit+=frontb-backa
    ans+=backa

if unit>0:
    ans+=backafrontb
else:
    if backafrontb>0:
        ans+=backafrontb-1
    else:
        ans+=0
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n=ii()
backa=0
frontb=0
backafrontb=0
ans=0
for i in range(n):
    s=list(ss())
    for j in range(len(s)-1):
        if s[j]+s[j+1]=="AB":
            ans+=1
    if s[0]=="B" and s[-1]=="A":
        backafrontb+=1
    elif s[0]=="B":
        frontb+=1
    elif s[-1]=="A":
        backa+=1
#print(backa,frontb,backafrontb,ans)

unit=0
if backa>=frontb:
    unit+=backa-frontb
    ans+=frontb
else:
    unit+=frontb-backa
    ans+=backa

if unit>0:
    ans+=backafrontb
else:
    ans+=backafrontb
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]

last_a = len([s for s in S if s[-1] == "A"])
first_b = len([s for s in S if s[0] == "B"])

cnt = sum(map(lambda x: x.count('AB'), S))

print(cnt + min(last_a, first_b))

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
tail_a_cnt = 0
top_b_cnt = 0
top_b_tail_a = 0
for i in range(n):
    s = list(input())
    top_b = False
    tail_a = False
    
    for c in range(len(s)):
        
        if c == 0:
            if s[c] == 'B':
                top_b = True
        else:
            if s[c] == 'B' and s[c-1] == 'A':
                ans += 1
        
        if c == len(s)-1 and s[c]=='A':
            tail_a = True
            
    top_b_cnt += top_b
    tail_a_cnt += tail_a
    top_b_tail_a += top_b*tail_a
   
ans += min(top_b_cnt, tail_a_cnt)
if top_b_cnt == tail_a_cnt == top_b_tail_a:
    ans -= 1
    
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
a = 0
b = 0
for _ in range(N):
    S = input()
    ans += S.count('AB')
    if S[0] == 'B':
        b += 1
    if S[-1] == 'A':
        a += 1

ans += min(a, b)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
cnt = 0
start = 0
end = 0
k = 0
for i in range(N):
    if "AB" in S[i]:
        cnt += 1
    if S[i][0] == "B":
        start += 1
    if S[i][-1] == "A":
        end += 1
    if S[i][0] == "B" and S[i][-1] == "A":
        k += 1
if start == end:
    print(cnt+min(start,end)-k)
else:
    print(cnt+min(start,end))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]


c = 0
ac = 0
bc = 0
abc = 0
for i in range(n):
    c += s[i].count('AB')
    if(s[i][-1] == 'A' and s[i][0] == 'B'):abc += 1
    elif(s[i][-1] == 'A'):ac += 1
    elif(s[i][0] == 'B'):bc += 1

c += max(0,abc - 1)
abc = min(abc,1)

if(ac < bc):ac += 1
else:bc += 1
print(c + min(ac,bc))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]


c = 0
ac = 0
bc = 0
abc = 0
for i in range(n):
    c += s[i].count('AB')
    if(s[i][-1] == 'A' and s[i][0] == 'B'):abc += 1
    elif(s[i][-1] == 'A'):ac += 1
    elif(s[i][0] == 'B'):bc += 1

# for i in range(abc):
#     if(ac < bc):ac += 1
#     else:bc += 1

print(c + min(ac+abc,bc+abc))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]


c = 0
ac = 0
bc = 0
for i in range(n):
    c += s[i].count('AB')
    if(s[i][-1] == 'A'):ac += 1
    if(s[i][0] == 'B'):bc += 1
print(c + min(ac,bc))

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.readline


def main():
    N = int(input())
    S = [""] * N
    for i in range(N):
        S[i] = input().rstrip()

    xABx = 0
    xxxA = 0
    Bxxx = 0
    BxxA = 0
    for s in S:
        xABx += s.count("AB")
        if s[0] == "B" and s[-1] == "A":
            BxxA += 1
        elif s[0] == "B":
            Bxxx += 1
        elif s[-1] == "A":
            xxxA += 1

    if xxxA == Bxxx == 0:
        ans = xABx + (BxxA - 1)
    else:
        ans = xABx + BxxA + min(xxxA, Bxxx)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    cunt_a=0
    cunt_b=0
    cunt_ba=0
    cunt_ab=0
    for i in range(n):
        s=input()
        if s[0]=='B' and s[-1]=='A':
            cunt_ba+=1
        elif s[0]=='B': 
            cunt_b+=1
        elif s[-1]=='A':
            cunt_a+=1
        for j in range(len(s)-1):
            if s[j:j+2]=="AB":
                cunt_ab+=1
    if cunt_a==0 and cunt_b==0:
        print(cunt_ab+cunt_ba-1)
    else:
        print(cunt_ab+cunt_ba+min(cunt_a,cunt_b))
    
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    cunt_a=0
    cunt_b=0
    cunt_ba=0
    cunt_ab=0
    for i in range(n):
        s=input()
        if s[0]=='B' and s[-1]=='A':
            cunt_ba+=1
        elif s[0]=='B': 
            cunt_b+=1
        elif s[-1]=='A':
            cunt_a+=1
        for j in range(len(s)-1):
            if s[j:j+2]=="AB":
                cunt_ab+=1
    print(cunt_ab+cunt_ba+min(cunt_a,cunt_b))

                
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
N=int(input())
s=[]
a=0
b=0
ab=0
aob=0

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

if a+aob==N:
    a-=1
if b+aob==N:
    b-=1
    
if a>b+aob:
    ans+=b+aob
elif b>a+aob:
    ans+=a+aob
else:
    ans+=min(a,b)+aob


print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
s=[]
a=0
b=0
ab=0
aob=0

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

if a>b+aob:
    ans+=b+aob
elif b>a+aob:
    ans+=a+aob
else:
    ans+=min(a,b)+aob

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i): is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## libs ##
from itertools import accumulate as acc, combinations as combi, product, combinations_with_replacement as combi_dup
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#

def main():
    n = II()
    ss = [IS() for i in range(n)]
    ab_type = {}
    ab_type['_ab_'] = 0
    ab_type['b__a'] = 0
    ab_type['___a'] = 0
    ab_type['b___'] = 0
    for s in ss:
        if s.find('AB') != -1:
            ab_type['_ab_'] += 1
        if s[0] == 'B' and s[-1] == 'A':
            ab_type['b__a'] += 1
        elif s[-1] == 'A':
            ab_type['___a'] += 1
        elif s[0] == 'B':
            ab_type['b___'] += 1
    cnt = 0
    cnt += ab_type['_ab_']
    if ab_type['b__a'] > 0:
        cnt += ab_type['b__a']-1
        if ab_type['___a'] > 0:
            cnt += 1
            ab_type['___a'] -= 1
        if ab_type['b___'] > 0:
            cnt += 1
            ab_type['b___'] -= 1
    cnt += min(ab_type['___a'], ab_type['b___'])
    print(cnt)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

mid_ab = 0
la_fb = 0
last_a = 0
first_b = 0

for s in moji:
    mojiretu=len(s)
    if s[0] == 'B' and s[-1] == 'A':
        la_fb += 1
    elif s[0] == 'B':
        first_b += 1
    elif s[-1] == 'A':
        last_a += 1
    for j in range(mojiretu-1):
        if s[j] == 'A' and s[j+1] == 'B':
            mid_ab += 1

if la_fb == 0:
    ans = mid_ab+min(last_a,first_b)
else:
    if la_fb <= abs(last_a-first_b):
        ans = mid_ab+min(last_a,first_b)+la_fb
    else:
        ans = mid_ab+max(last_a,first_b)+(la_fb-abs(last_a-first_b))
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
a = 0
b = 0
ryou = 0
for _ in range(n):
    tmp = input()
    ans += tmp.count('AB')
    if tmp[0] == 'B':
        if tmp[-1] == 'A':
            ryou += 1
        else:
            b += 1
    elif tmp[-1] == 'A':
        a += 1

if ryou > 1:
    ans += (ryou-1)
    ryou = 1
#print(ans)
diff = abs(b-a)
if diff > ryou:
    ans += min(a,b)+ryou
else:
    nokori = ryou -diff
    ans += max(a,b)+nokori//2
    #print(ans,a,b,ryou,diff,max(a,b),nokori//2)
#print(ans,a,b,ryou,diff,max(a,b),nokori//2)
print(ans)