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())

count = 0
frontb = 0
lasta = 0

for _ in range(n):
  s = input()
  if s[0] is "B":
    frontb += 1
  if s[-1] is "A":
    lasta += 1
b,a,ba = n-lasta,n-frontb,frontb+lasta-n

if ba > 0:
  count+= ba-1
  if a>0 or b>0:
    count+=1
count += min(a,b) 
    
print(count)

Submission status: Wrong Answer

Solution code:
N = int(input())
a, b, c = 0, 0, 0
ans = 0

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

if a != b:
    ans += 1
if c > 0:
    ans += c-1

print(ans + min(a, b))

Submission status: Wrong Answer

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

b_start = []
a_end = []
count = 0
dob = 0
for i in s:
  b_flag = False
  a_flag = False
  if "AB" in i:
    count += 1
  if i[0] == "B":
    b_start.append(i)
    b_flag = True
  if i[-1] == "A":
    a_end.append(i)
    a_flag = True
  if b_flag and a_flag:
    dob += 1
    
count += min(len(b_start), len(a_end))
print(count)

Submission status: Wrong Answer

Solution code:
n=int(input())
b_start=0
a_last=0
both=0
ans=0
for i in range(n):
    s=input()
    ans+=s.count("AB")
    if s[0]=="B":
        if s[len(s)-1]=="A":
            both+=1
        else:
            b_start+=1
    elif s[len(s)-1]=="A":
        a_last+=1
diff=abs(b_start-a_last)
if diff==0:
    print(max(b_start,a_last)+max(0,(both-1))+ans)
elif diff >= both:
    print(min(b_start,a_last)+both+ans)
else:
    print(max(b_start,a_last)+(both-diff)+ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for i in range(n)]
cnt = 0
a = 0
b = 0
for i in range(n):
    cnt += S[i].count("AB")
    if S[i].startswith("B"):
        a += 1
    if S[i].endswith("A"):
        b += 1
if min(a, b) == n:
    print(cnt + n - 1)
else:
    print(cnt + min(a, b))

Submission status: Wrong Answer

Solution code:
import sys
from fractions import gcd
from functools import reduce
from itertools import combinations
from math import factorial

import numpy as np

sys.setrecursionlimit(200000)


def input():
    return sys.stdin.readline()[:-1]


def ii(t: type = int):
    return t(input())


def il(t: type = int):
    return list(map(t, input().split()))


def imi(N: int, t: type = int):
    return [ii(t) for _ in range(N)]


def iml(N: int, t: type = int):
    return [il(t) for _ in range(N)]


def solve():
    N = ii()
    # S = imi(N, str)
    first_B = []
    last_A = []
    num_AB = 0
    # 重複要素
    dupl = []
    for _ in range(N):
        s = ii(str)
        num_AB += s.count("AB")
        if s[0] == "B" and s[-1] == "A":
            dupl.append(s)
            continue
        if s[0] == "B":
            first_B.append(s)
        if s[-1] == "A":
            last_A.append(s)
    comb_AB = min(len(first_B), len(last_A))
    ans = num_AB + comb_AB + factorial(len(dupl))
    return ans


if __name__ == "__main__":
    print(solve())

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [str(input()) for i in range(N)]
ans = 0
a = 0
b = 0
ab = 0
for i in range(N):
    ans += s[i].count('AB')
    if s[i][0] == 'B' and not s[i][-1] == 'A':
        b += 1
    if s[i][-1] == 'A' and not s[i][0] == 'B':
        a += 1
    if s[i][0] == 'B' and s[i][-1] == 'A':
        ab += 1
ans += min(a,b)
ans += min(ab,min(a,b))
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
s = list()
counter = {
    'ab': 0,
    'begin_b': 0,
    'end_a': 0,
    'b_to_a': 0
}

for i in range(n):
    substr = input()
    counter['ab'] += substr.count('AB')
    if substr.startswith('B'):
        counter['begin_b'] += 1
        if substr.endswith('A'):
            counter['b_to_a'] += 1
    if substr.endswith('A'):
        counter['end_a'] += 1

num_joint = min(counter['begin_b'], counter['end_a'])
if num_joint > 0 and counter['begin_b'] == counter['end_a'] and counter['b_to_a'] > 0:
    num_joint -= 1
total = counter['ab'] + num_joint

print(total)

Submission status: Wrong Answer

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

base = sum(x.count('AB') for x in s)

same_pattern = a_n = b_n = 0
for x in s:
    b = x[0]
    a = x[len(x)-1]
    if b == 'B':
        b_n += 1
    if a == 'A':
        a_n += 1
    if a == 'A' and b == 'B':
        same_pattern += 1

if same_pattern > 0 and same_pattern == min(a_n, b_n):
    print(base + min(a_n, b_n) - 1)
else:
    print(base + min(a_n, b_n))

Submission status: Wrong Answer

Solution code:
target = "AB"
N = int(input())
ans = 0
finish_A = set()
start_B = set()
for i in range(N):
    s = input()
    lens = len(s)
    index = 0
    if s[-1] == "A":
        finish_A.add(i)
    if s[0] == "B":
        start_B.add(i)
    while index <= lens-2:
        if s[index:index+2] == target:
            ans += 1
            index += 2
            continue
        index += 1
both = len(finish_A & start_B)
onlyA = len(finish_A) - both
onlyB = len(start_B) - both
if onlyA < onlyB:
    print(str(ans + onlyA + both))
elif onlyB < onlyA:
    print(str(ans + onlyB + both))
elif both == 0:
    print(str(ans + onlyA))
else:
    print(str(ans + onlyA + both - 1))

Submission status: Wrong Answer

Solution code:
a = int(input())
s = 0
A=B=AB=0

d = {"A":0,"B":0}
for i in range(a):
    t = input()
    s+=t.count("AB")
    if t[0]=="B" and t[-1]=="A":AB+=1
    elif t[0]=="B":B+=1
    elif t[-1]=="A":A+=1
res = 0
res += min(A,B)
if AB>0 and abs(A-B):
    res+=AB
else:
    res+=AB-1
print(res+s)

Submission status: Wrong Answer

Solution code:
N = int(input())
left, right, both = 0, 0, 0
ans = 0
for i in range(N):
    s = input()
    if s[0] == "B":
        if s[-1] == "A":
            both += 1
        else:
            left += 1
    elif s[-1] == "A":
        right += 1
    for j in range(len(s) - 1):
        if s[j] == "A" and s[j + 1] == "B":
            ans += 1
# print(left, right, both, ans)

if min(left, right) >= 1:
    bonus = min(left, right) + both

elif max(left, right) == 0:
    bonus = min(both - 2, 0)

else:
    bonus = both

print(ans + bonus)

Submission status: Wrong Answer

Solution code:
N = int(input())
L = []

for i in range(N):
    L.append(input())
    
a = 0
b = 0
ab = 0
ans = 0
for i in range(N):
    s = L[i]
    ab = s.count("AB")
    ans += ab

    if s[0] is "B":
        b += 1
    if s[-1] is "A":
        a += 1
        
ans += min(a, b)



print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())

count = 0
count_a = 0
count_b = 0
for i in range(n):
    s = input()
    if 'AB' in s[1:-1]:
        count += 1
    
    if s[0] == 'B':
        count_b += 1

    if s[-1] == 'A':
        count_a += 1

#print('(count, A, B)=({}, {}, {})'.format(count, count_a, count_b))

ans = count + min(count_a, count_b)

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
c = 0
tail_A = 0
head_B = 0
B_A = 0
def count(S):
    if len(S) == 1:
        return 0
    c = 0
    for i in range(len(S)-1):
        if S[i] == 'A' and S[i+1] == 'B':
            c += 1
    return c

for _ in range(N):
    s = input()
    c += count(s)
    if s[-1] == 'A':
        if s[0] == 'B':
            B_A += 1
        else:
            tail_A += 1
    else:
        if s[0] == 'B':
            head_B += 1

if tail_A > 0 and head_B > 0:
    c = c + B_A + 1
    tail_A -= 1
    head_B -= 1
elif tail_A == 0 and head_B > 0:
    c = c + B_A
    head_B -= 1
elif tail_A > 0 and head_B == 0:
    c = c + B_A
    tail_A -= 1

c += min(tail_A, head_B)
print(c)

Submission status: Wrong Answer

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

ans = 0
A = B = BA = 0
for s in S:
    for i in range(len(s) - 1):
        if s[i] + s[i + 1] == 'AB':
            ans += 1

    if s[-1] == 'A' and s[0] == 'B':
        BA += 1
    elif s[-1] == 'A':
        A += 1
    elif s[0] == 'B':
        B += 1

if A & B:
    ans += BA + 2
    A, B = A - 1, B - 1
    ans += min(A, B)

elif A:
    ans += BA
elif B:
    ans += BA

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = []
count = 0
countA = 0
countB = 0
countAB = 0
for i in range(N):
	S_in = str(input())
	for j in range(len(S_in)-1):
		if S_in[j:j+2] == 'AB':
			count += 1
	if (S_in[0] == 'B') & (S_in[-1] == 'A'):
		countAB	+= 1
	elif S_in[0] == 'B':
		countB += 1
	elif S_in[-1] == 'A':
		countA += 1
	S.append(S_in)
if (countA == 0) & (countB == 0):
	print(max(0, count + countAB - 1))
else:
	print(count + countAB + min(countA, countB))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N = int(input())
S = [input() for _ in range(N)]
l, m, n = 0, 0, 0
ans = 0
for s in S:
    if s[0] == 'B' and s[-2] == 'A':
        n += 1
    elif s[0] == 'B':
        m += 1
    elif s[-2] == 'A':
        l += 1
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            ans += 1

if l == 1 and m == 1 and n == 0:
    ans += 1
else:
    p = min(l, m)
    n += p
    m -= p
    l -= p
    if n > 0:
        ans += n - 1
    if n > 0 and l != m:
        ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())

#normal, start_b, end_a, both

kosu=0
tokushu=[0,0,0,0]

for i in range(n):
    line=input()
    switch=0
    for l in range(len(line)):
        if switch==1:
            if line[l]=='B':
                kosu+=1
            else:
                switch=0
        if line[l]=='A':
            switch=1
    
    if line[0]=='B':
        if line[-1]=='A':
            tokushu[3]+=1
        else:
            tokushu[1]+=1
    else:
        if line[-1]=='A':
            tokushu[2]+=1
        else:
            tokushu[0]+=1

#print(kosu)
#print(tokushu)
#gacchi=min(tokushu[1], tokushu[2])
#gacchi2=min(tokushu[3], max(tokushu[1]-gacchi, tokushu[2]-gacchi))

if tokushu[1]>tokushu[2]:
    gacchi=tokushu[2]
    nokori=tokushu[1]-gacchi
    if nokori>=tokushu[3]:
        gacchi2=tokushu[3]
    else:
        gacchi2=tokushu[3]
else:
    gacchi=tokushu[1]
    nokori=tokushu[2]-gacchi
    if nokori>=tokushu[3]:
        gacchi2=tokushu[3]
    else:
        gacchi2=tokushu[3]
    
#print(gacchi,gacchi2)
print(kosu+gacchi+gacchi2)

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt = 0
a = 0
b = 0
f = 0
for i in range(n):
  s = input()
  cnt += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    f += 1
  elif s[0] == 'B':
    b += 1
  elif s[-1] == 'A':
    a += 1

if a >= 1:
  cnt += 1
  a -= 1
if b >= 1:
  cnt += 1
  b -= 1
print(cnt + f - 1 + min(a, b))

Submission status: Wrong Answer

Solution code:
l = raw_input().split()
N = int(l[0])
S = [0]*N
for i in range(N):
    l = raw_input().split()
    S[i] = l[0]

#print(N, S)

count = 0
for s in S:
    count += s.count('AB')
#print(count)

numA = 0
numB = 0
numAB = 0
for s in S:
    if s[0] != 'B' and s[-1] == 'A':
        numA += 1
    if s[0] == 'B' and s[-1] != 'A':
        numB += 1
    if s[0] == 'B' and s[-1] == 'A':
        numAB += 1

count += min(numA, numB)
diff = max(numA, numB) - min(numA, numB)
count += min(diff, numAB)
if numAB > diff:
    remain = numAB - diff
    count += remain - 1
print(count)

Submission status: Wrong Answer

Solution code:
from sys import stdin
import math
import itertools


def makeIntMatrix(lines):
    intMatrix = []
    for a in makeStringMatrix(lines):
        intMatrix.append([int(b) for b in a])
    return intMatrix
 
 
def makeStringMatrix(lines):
    stringMatrix = [line.rstrip() for line in lines]
    return stringMatrix
 
 
def makeInt(line):
    return int(line.rstrip())
 
 
def makeMultiInteger(line):
    return [int(x) for x in line.rstrip().split()]


def solve(input_string):
    N = makeInt(input_string[0])
    S = makeStringMatrix(input_string[1:])
    print(S)
    C_S_has_ab = []
    for s_index, s in enumerate(S):
        C_S_has_ab.append(0)
        for i in range(len(s)-1):
            if s[i] + s[i+1] == 'AB':
                C_S_has_ab[s_index] += 1
    print(C_S_has_ab)
    _sum = 0
    _sum += sum(C_S_has_ab) 
    c_head_has_b = 0
    c_tail_has_a = 0
    c_head_tail_has_a_and_b = 0
    for s in S:
        if s[0] == 'B':
            c_head_has_b += 1
        if s[-1] == 'A':
            c_tail_has_a += 1
        if s[0] == 'B' and s[-1] == 'A':
            c_head_tail_has_a_and_b += 1
    print(c_tail_has_a, c_tail_has_a, c_head_tail_has_a_and_b)
    #count_combi_a_b = c_tail_has_a * c_tail_has_a - c_head_tail_has_a_and_b
    count_combi_a_b = min(c_tail_has_a, c_tail_has_a) - c_head_tail_has_a_and_b + 1
    #- c_head_tail_has_a_and_b
    _sum += count_combi_a_b
    print(_sum)
    return _sum


def main():
    input_lines = stdin.readlines()
    answer = solve(input_lines)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(N: int, s: "List[str]"):
    ABcount = 0
    Aend = 0
    Bstart = 0
    AendBstart = 0
    for i in range(N):
        if "AB" in s[i]:
            ABcount += 1
        if s[i][0] == "B":
            if s[i][-1] == "A":
                AendBstart += 1
            else:
                Bstart += 1
        elif s[i][-1] == "A":
            Aend += 1

    if AendBstart > 1:
        ABcount += AendBstart - 1
        AendBstart = 1
    ABcount += min(Aend, Bstart)+AendBstart
    print(ABcount)

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    s = [next(tokens) for _ in range(N)]  # type: "List[str]"
    solve(N, s)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N=int(input())
# 3
# BAA
# BWA
# BBA
s_list = [input() for i in range(N)]
AB_count = sum(map(lambda s: s.count('AB'), s_list))
tail_A = sum(map(lambda s: s[-1]=='A', s_list))
head_B = sum(map(lambda s: s[0]=='B', s_list))
pair = sum(map(lambda s: s[0]=='B' and s[-1]=='A', s_list))
print(AB_count + min(tail_A, head_B) - (tail_A == head_B and tail_A == pair))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for i in range(n)]
count = 0
count_a = 0
count_b = 0
count_ab = 0
for i in range(n):
    count += s[i].count("AB")
    if s[i][-1] == "A":
        count_a += 1
    if s[i][0] == "B":
        count_b += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        count_ab += 1

# print([count,count_a,count_b,count_ab])

if n == 1:
    print(count)
# elif count_ab%2 == 0:
#     print(count+min([count_a,count_b]))
else:
    print(count+min([count_a,count_b]))

Submission status: Wrong Answer

Solution code:
from sys import stdin
input=[]
input1=stdin.readline().rstrip()
N=int(input1[0])
for n in range(N):
  input.append(stdin.readline().rstrip())
#print(input)

output=0
count_A=0
count_B=0
for i in range(len(input)):
    if "AB" in input[i]:
        output+=input[i].count("AB")
    if "A" in input[i][len(input[i])-1]:
        count_A+=1
        #continue
    if "B" in input[i][0]:
        count_B+=1

if count_A<count_B:
    print(output+count_A)
else:
    print(output+count_B)

Submission status: Wrong Answer

Solution code:
N=int(input())
a=0
b=0
c=0
d=0

for i in range(N):
    S=str(input())
    s=len(S)
    for i in range(s-1):
        if S[i]=="A" and S[i+1]=="B":
            d+=1
    if S[0]=="B" and S[s-1]=="A":
        a+=1
    elif S[0]=="B":
        b+=1
    elif S[s-1]=="A":
        c+=1

if b==0 or c==0:
    print(a+d)
else:

    b=max(b,c)
    c=min(b,c)

    e=b-c

    if e>=a:
        print(a+c+d)
    else:
        print(a-1+c+d)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = []
A, B, AB, BA = 0, 0, 0, 0
for i in range(N):
    a = input()
    S.append(a)
    if a[0] == 'B' and a[-1] == 'A':
        BA += 1
    elif a[0] == 'B':
        B += 1
    elif a[-1] == 'A':
        A += 1
    AB += a.count('AB')
ans = 0

ans += AB + min(A, B)
ans += BA
if A == B and BA > 0:
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
ans = 0
for i in range(N):
    si = input()
    s.append(si)

    ans += si.count("AB")




d = {}
d["A"] = 0
d["B"] = 0
d["all"] = 0

for i in range(N):
    if s[i][0] == "B" and s[i][-1] == "A":
        d["all"] += 1
    elif s[i][0] == "B":
        d["B"] += 1
    elif s[i][-1] == "A":
        d["A"] += 1


c = min(d["A"],d["B"],d["all"])
ans += (c*2)
d["A"] -= c
d["B"] -= c
d["all"] -= c

if d["all"] == 0:
    ans += min(d["A"],d["B"])
elif d["A"] == 0:
    ans += 2*min(d["all"]//2,d["B"])
elif d["B"] == 0:
    ans += 2*min(d["all"]//2,d["A"])


print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for i in range(n)]
cnt = 0
a = 0
b = 0
for i in range(n):
    cnt += S[i].count("AB")
    if S[i].startswith("B"):
        a += 1
    if S[i].endswith("A"):
        b += 1
if min(a, b) == 0:
    print(cnt + n - 1)
else:
    print(cnt + min(a, b))

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[5]:

import sys
input = sys.stdin.readline
N = int(input())
S = [input() for i in range(N)]


# In[12]:

b_cnt = 0
a_cnt = 0
ab_cnt = 0
for i in range(N):
    if S[i][0]=='B'and S[i][-1]=='A':
        ab_cnt += 1
    elif S[i][0]=='B':
        b_cnt += 1
    elif S[i][-1]=='A':
        a_cnt += 1
#print(b_cnt, a_cnt)
#print(ab_cnt, a_cnt, b_cnt, '/'.join(S).count('AB') )
if abs(a_cnt-b_cnt) == 1 and ab_cnt > 0:
    ab_cnt += 1
    
#if ab_cnt < 0:
#    ab_cnt = 0
#ab_cnt = ab_cnt-1 if ab_cnt!=0 else ab_cnt
print('/'.join(S).count('AB') + min(a_cnt, b_cnt, N-1) + ab_cnt)


# In[ ]:

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
ab_num = 0
b_start = 0
a_end = 0
ba_word = 0
for i in range(N):
    tmp = input()
    s.append(tmp)
    rep = tmp.replace("AB", "")
    ab_num += (len(tmp) - len(rep)) // 2
    if tmp[0] == "B":
        b_start += 1
    if tmp[-1] == "A":
        a_end += 1
    if tmp[0] == "B" and tmp[-1] == "A":
        ba_word += 1
if b_start == a_end == ba_word:
    print(max(ab_num + min(a_end, b_start) - 1, 0))
else:
    print(ab_num + min(a_end, b_start))

Submission status: Wrong Answer

Solution code:
N = int(input())
numA = 0
numB = 0
ans = 0
for i in range(N):
    cand = list(input())
    if cand[-1] == 'A':
        numA += 1
    if cand[0] == 'B':
        numB += 1
    ind = 0
    while ind < len(cand):
        try:
            ind = cand.index('A', ind)
            if ind + 1 < len(cand):
                if cand[ind + 1] == 'B':
                    ans += 1
            ind += 1
        except:
            break
print(ans + min(numA, numB))

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for _ in range(n)]
cnt = 0
fb_cnt = 0
ba_cnt = 0
for s in S:
    idx = len(s) - 1
    for i in range(idx - 1):
        if s[i] == 'A' and s[i + 1] == 'B':
            cnt += 1
    if s[idx] == 'A':
        ba_cnt += 1
    if s[0] == 'B':
        fb_cnt += 1

min_cnt = min(fb_cnt, ba_cnt)
min_cnt = min_cnt - 1 if n <= min_cnt else min_cnt
print(cnt + min_cnt)

Submission status: Wrong Answer

Solution code:
N=int(input())

naiv=0
endsA=0
startsB=0
both=0


for i in range(N):
    s=input()
    naiv+=s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[0] == 'B':
        startsB += 1
    elif s[-1] == 'A':
        endsA += 1

# print("endsA {}".format(endsA))
# print("startsB {}".format(startsB))
# print("both {}".format(both))
# print("naiv {}".format(naiv))

res=naiv
if both >= startsB and both >= endsA:
    res += min(endsA, startsB)*2
    both -= min(endsA, startsB)
    res += both
    both = 0
elif both <= startsB and both <= endsA:
    res += both*2
    endsA -= both
    startsB -= both
    both = 0
    res += min(endsA, startsB)
else:
    lower = min(endsA, startsB)
    res += 2*lower
    both -= lower
    endsA -= lower
    startsB -= lower
    res += both

print(res)

Submission status: Wrong Answer

Solution code:
n = int(input())
inab = 0
topb = 0
taila = 0
topb_taila = 0
for _ in range(n):
    s = str(input())
    if (s[0] == "B")&(s[-1] == "A"):
        topb_taila += 1
    else:
        if (s[0] == "B"):
            topb += 1
        if (s[-1] == "A"):
            taila += 1
    
    bef =""
    for i in range(len(s)):
        if (bef=="A")&(s[i]=="B"):
            inab += 1
        bef = s[i]

ans = inab
if topb_taila == 0:
    ans += min(taila,topb)
elif topb_taila == 1:
    if taila!=topb:
        ans += 1+min(taila,topb)
    else:
        ans += min(taila,topb)
else:
    if taila!=topb:
        ans += (topb_taila)+min(taila,topb)
    else:
        ans += (topb_taila-1)+min(taila,topb)
print(ans)

Submission status: Wrong Answer

Solution code:
#python 3.5.2

N = int(input())
s_list = [input() for i in range(N)]
cnt = sum([1 for s in s_list if "AB" in s])
a_end, b_start, a_b = 0, 0, 0
for s in s_list:
    if s[0] == "B" and s[-1] == "A":
        a_b += 1
    elif s[0] == "B":
        b_start += 1
    elif s[-1] == "A":
        a_end += 1
cnt += min(a_end, b_start)
sabun = abs(a_end - b_start)
if sabun >= a_b:
    cnt += a_b
else:
    cnt += sabun + int((a_b - sabun)/2) + 1
print(cnt)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()


def main():
    n = int(input())

    a = b = mi = 0

    for i in range(n):
        s = input()
        mi += s.count('AB')
        a += s[-1] == 'A'
        b += s[0] == 'B'

    print(mi + min(a, b, n - 1))


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = "x" in file.mode or "r" not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
onlytop = False
onlytail = False
topb = 0
taila = 0
counter = 0
for i in range(n):
    stmp = input()
    flag = False
    if stmp[0] == 'B':
        topb+=1
        if stmp[-1] == 'A':
            taila += 1
        else:
            onlytop = True
    elif stmp[-1] == 'A':
        taila +=1
        onlytail = True
    for i in stmp:
        if flag and i == 'B':
            counter += 1
        flag = False
        if i == 'A':
            flag = True
print('counter is ', counter)
if topb == taila:
    print(topb - 2 + onlytail + onlytop + counter)
else:
    print(min(topb,taila) - 1 + onlytail + onlytop + counter)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = 0
b = 0
ab = 0
b_a = 0
for i in range(n):
    s = input()
    if s[0] == "B" and s[-1] == "A":
        b_a += 1
    elif s[0] == "B":
        b += 1
    elif s[-1] == "A":
        a += 1
    for j in range(len(s) - 1):
        if s[j] == "A" and s[j + 1] == "B":
            ab += 1
if a > b:
    a, b = b, a
ans = ab
if b_a <= b:
    ans += a + b_a
else:
    ans += a * 2 + b_a
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
s = list()
counter = {
    'ab': 0,
    'begin_b': 0,
    'end_a': 0,
    'b_to_a': 0
}

for i in range(n):
    substr = input()
    counter['ab'] += substr.count('AB')
    if substr.startswith('B'):
        counter['begin_b'] += 1
        if substr.endswith('A'):
            counter['b_to_a'] += 1
    if substr.endswith('A'):
        counter['end_a'] += 1

num_joint = min(counter['begin_b'], counter['end_a'])
if num_joint > 1 and counter['begin_b'] == counter['end_a'] and counter['b_to_a'] > 0:
    num_joint -= 1
total = counter['ab'] + num_joint

print(total)

Submission status: Wrong Answer

Solution code:
N = int(input())
S_tail_a_head_b = []
S_tail_a = []
S_head_b = []
S_ab = []
for _ in range(N):
    s = input()
    if s.find('AB') == -1 and s[0] != 'B' and s[-1] != 'A':
        continue
    elif s[0] == 'B' and s[-1] == 'A':
        S_tail_a_head_b.append(s)
    elif s[0] == 'B':
        S_head_b.append(s)
    elif s[-1] == 'A':
        S_tail_a.append(s)
    else:
        S_ab.append(s)

S = ''.join(S_ab)
tail_a = ''
head_b = ''
for i in range(max(len(S_head_b), len(S_tail_a))):
    if len(S_head_b) > i and len(S_tail_a) > i:
        S += S_tail_a[i] + S_head_b[i]
    elif len(S_head_b) <= i:
        tail_a = ''.join(S_tail_a[i:])
        break
    else:
        head_b = ''.join(S_head_b[i:])
        break

S += tail_a + ''.join(S_tail_a_head_b) + head_b

print(S.count('AB'))

Submission status: Wrong Answer

Solution code:
N=int(input())
s=' '
num_AB=0
num_A=0
num_B=0
for i in range(0,N):
    s=str(input())
    if(s[0]=='B'):
        num_B+=1
    if(s[-1]=='A'):
        num_A+=1
    for j in range(0,len(s)-1):
        if(s[j]=='A' and s[j+1]=='B'):
            num_AB+=1;
ext=min(num_A,num_B)
#junctionがN-1個よりも大きくなることはない
ext=min(ext,N-1)
ans=num_AB+ext
print(ans)

Submission status: Wrong Answer

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

c = 0
ca = 0
cb = 0
cab = 0

for s in sl:
  c += s.count('AB')
  if s[-1] == 'A':
    ca += 1
  if s[0] == 'B':
    cb += 1
  if s[-1] == 'A' and s[0] == 'B':
    cab += 1

t = min(ca, cb)
if ca == cb and cb == cab:
  t -= 1
print(c + t)

Submission status: Wrong Answer

Solution code:
N = int(input())
s_list = []
ans = 0

b_head_a_tail = 0
b_head = 0
a_tail = 0

for _ in range(N):
    string= input()
    if string[0] == "B":
        if string[-1] == "A":
            b_head_a_tail += 1
        else:
            b_head += 1
    elif string[-1] == "A":
        a_tail += 1
    if "AB" in string:
        ans += 1
        
if b_head_a_tail > 0:
    if a_tail > 0:
        if b_head > 0:
            ans += b_head_a_tail  + min(a_tail, b_head) 
        else:
            ans += b_head_a_tail
    else:
        if b_head > 0:
            ans += b_head_a_tail
        else:
            ans += b_head_a_tail - 1
else:
    ans += min(a_tail, b_head) 
    
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [list(input()) for i in range(n)]
a,b,c = 0,0,0
t = 0
for i in range(n):
        for j in range(len(s[i])-1):
                if s[i][j] == "A" and s[i][j+1] == "B":
                        c += 1
        if s[i][0] == "B":
                b += 1
        if s[i][-1] == "A":
                a += 1
        if s[i][0] == "B" and s[i][-1] == "A":
                t += 1

if a > b:
        d = b
else:
        d = a

if t == a:
        d -= 1

print(d + c)

Submission status: Wrong Answer

Solution code:
n=int(input())
ss=[]
for _ in range(n):
    s=input()
    if 'A' in s or 'B' in s:
        ss.append(s)
c = sum(s.count('AB') for s in ss)
c += min(sum(s[0] == 'B' for s in ss), sum(s[-1] == 'A' for s in ss))
if sum((s[0] == 'B' and s[-1] != 'A') or (s[0] != 'B' and s[-1] == 'A') for s in ss) == 0:
    c -= 1
print(c)

Submission status: Wrong Answer

Solution code:
N = int(input())

b = 0
a = 0
count = 0
check = -1
for i in range(N):
    s = input()
    count += len([1 for j in range(len(s)) if s[j:j + 2] == "AB"])
    if s[-1] == "A":
        a += 1
    if s[0] == "B":
        b += 1
    if s[0] == "B" and s[-1] == "A":
        check += 1

if a == b and b == check:
    print(count+b-1)
else:
    print(count + min([a, b, check]))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
f1, f2, f3 = 0, 0, 0
ans = 0
for i in range(n):
    t = input(); s.append(t)
    ans += t.count("AB")
    if t[0] == "B" and t[-1] != "A":
        f1 += 1
    if t[0] != "B" and t[-1] == "A":
        f2 += 1
    if t[0] == "B" and t[-1] == "A":
        f3 += 1
# f1: B....X
# f2: X....A
# f3: B....A
if f1 == 0:
    ans += min(f2, f3)
    if f2 == 0:
        ans += max(0, f3-1)
    else:
        t = min(f2, f3)
        ans += t
        f2 -= t
        f3 -= t
        ans += f3

elif f2 == 0:
    ans += min(f1, f3)
elif f3 == 0:
    ans += min(f1, f2)
else:
    ans += min(f2, f3)
    t = min(f2, f3)
    f2 -= t
    f3 -= t

    if f3 == 0:
        f2 += 1
        ans += min(f1, f2)
    elif f2 == 0:
        ans += f3
        ans += 1

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

def solve():
    NAB, NBA, NB_, N_A = 0, 0, 0, 0
    for _ in range(int(input())):
        S = input()
        NAB += S.replace('AB', '-').count('-')
        b, a = S.startswith('B'), S.endswith('A')
        NBA += b&a
        NB_ += b&(~a)
        N_A += (~b)&a
    res = NAB + max(NBA-1, 0) + (NB_>=1) + (N_A>=1) + max(min(NB_, N_A)-1, 0)

    return str(res)

if __name__ == '__main__':
    print(solve())

Submission status: Wrong Answer

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

    AB = 0
    B_ = 0
    _A = 0
    B_A = 0
    for ss in s:
        if 'AB' in ss:
            AB += 1
        if ss[0] == 'B':
            if ss[-1] == 'A':
                B_A += 1
            else:
                B_ += 1
        elif ss[-1] == 'A':
            _A += 1
    print(AB + max((B_A - 1), 0) + max(min(B_ + int(B_A > 0), _A), min(B_, _A + int(B_A > 0))))
    # print(AB, B_, _A, B_A)

if __name__ == '__main__':
    main()