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: Accepted

Solution code:
# coding: utf-8

import sys
input = sys.stdin.readline

N = int(input())
# L = [int(x) for x in input().split()]
# N, K = map(int, input().split())

AB  = 0
xA = 0
BxA = 0
Bx = 0

for _ in range(N) :
    S = input()

    AB += S.count("AB")

    if S[0] + S[-2] == "BA" :
        BxA += 1
    elif S[-2] == 'A' :
        xA += 1
    elif S[0] == 'B' :
        Bx += 1

if BxA == 0 :
    print(AB + min(xA, Bx))
elif BxA == 1 and xA <= 1 and Bx <= 1 :
    print(AB + xA + Bx)
elif BxA == 1 and (xA == 0 or Bx == 0) :
    print(AB + 1)
elif BxA == 1 :
    print(AB + min(xA - 1, Bx - 1) + 2)
elif xA <= 1 and Bx <= 1 :
    print(AB + xA + Bx + (BxA - 1))
elif xA == 0 or Bx == 0 :
    print(AB + BxA)
else :
    print(AB + min(xA - 1, Bx - 1) + 2 + (BxA - 1))

Submission status: Accepted

Solution code:
n = int(input())
list = []
for i in range(n):
    keep = input()
    list.append(keep)
double = 0
b = 0
a = 0
include = 0
for j in range(n):
    if list[j][0] == "B" and list[j][-1:] == "A":
        double += 1
    elif list[j][0] == "B":
        b += 1
    elif list[j][-1:] == "A":
        a += 1
for k in range(n):
    keep_len = len(list[k])
    for l in range(keep_len-1):
        if list[k][l] == "A" and list[k][l+1] == "B":
            include += 1
if b == 0 and a == 0 and double == 0:
    print(include)
elif b == 0 and a == 0:
    print(double-1 + include)
elif b == 0 or a == 0:
    print(double-1 + include + 1)
else:
    print(double-1 + include + min(b, a) + 1)

Submission status: Accepted

Solution code:
import re


def main():
    N = int(input())  # 10^4
    b__a = 0
    b___ = 0
    ___a = 0
    tmp = 0
    ans = 0
    for i in range(N):
        tmp = input()
        if (tmp[0] == 'B') and (tmp[-1] == 'A'):
            b__a += 1
        elif (tmp[0] == 'B'):
            b___ += 1
        elif (tmp[-1] == 'A'):
            ___a += 1

        ans += len(re.findall('AB', tmp))

    if b__a == 0:
        ans += min(b___, ___a)
    else:
        if (b___ + ___a) > 0:
            ans += b__a + min(b___, ___a)
        elif (b___ + ___a) == 0:
            ans += b__a - 1

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    from sys import stdin, stdout
 
    def read():
        return stdin.readline().rstrip('\n')
 
    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)
 
    def read_int():
        return int(read())
 
    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]
 
    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)
 
    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)
 
    n = read_int()
    b_starts = 0
    a_ends = 0
    both = 0
    count = 0
 
    for i in range(n):
        word = read().strip()
        for i in range(1, len(word)):
            if word[i-1] == 'A' and word[i] == 'B':
                count += 1
 
        if word[0] == 'B' and word[-1] == 'A':
            both += 1
        elif word[-1] == 'A':
            a_ends += 1
        elif word[0] == 'B':
            b_starts += 1
 
    if a_ends > 0 and b_starts > 0:
        count += both + 1
        a_ends -= 1
        b_starts -= 1
    elif a_ends > 0:
        count += both
        a_ends -= 1
    elif b_starts > 0:
        count += both
        b_starts -= 1
    elif both:
        count += both - 1
    count += min(a_ends, b_starts)
 
    write(count)
 
main()

Submission status: Accepted

Solution code:
def main():
    from sys import stdin, stdout

    def read():
        return stdin.readline().rstrip('\n')

    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)

    def read_int():
        return int(read())

    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]

    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)

    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)

    n = read_int()
    b_starts = 0
    a_ends = 0
    both = 0
    count = 0

    for i in range(n):
        word = read().strip()
        for i in range(1, len(word)):
            if word[i-1] == 'A' and word[i] == 'B':
                count += 1

        if word[0] == 'B' and word[-1] == 'A':
            both += 1
        elif word[-1] == 'A':
            a_ends += 1
        elif word[0] == 'B':
            b_starts += 1

    if a_ends > 0 and b_starts > 0:
        count += both + 1
        a_ends -= 1
        b_starts -= 1
    elif a_ends > 0:
        count += both
        a_ends -= 1
    elif b_starts > 0:
        count += both
        b_starts -= 1
    elif both:
        count += both - 1
    count += min(a_ends, b_starts)

    write(count)

main()

Submission status: Accepted

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

ans = 0
start_B = 0
end_A = 0
B_A = 0
for s in s_list:
  ans += s.count("AB")
  if s[0] == "B" and s[-1] == "A":
    B_A += 1
  elif s[0] == "B":
    start_B += 1
  elif s[-1] == "A":
    end_A += 1

if B_A > 0 and start_B + end_A == 0:
  ans += B_A - 1
else:
  ans += min(start_B, end_A) + B_A

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = []
for i in range(0, n):
    s.append(input())
 
c = 0
a = 0
b = 0
ab = 0
 
for i in range(0, n):
    for j in range(1, len(s[i])):
        if s[i][j-1:j+1] == "AB":
            c += 1
    if s[i][-1] == "A" and s[i][0] == "B":
        ab += 1
    else: 
        if s[i][0] == "B":
            b += 1
        if s[i][-1] == "A":
            a += 1
            
s = c
 
if ab > 0:
    s += ab - 1
    if a > 0:
        s += 1
        a -= 1
    if b > 0:
        s += 1
        b -= 1
 
s += min(a, b)
 
print(s)

Submission status: Accepted

Solution code:
N = int(raw_input())

inner_ab_count = 0
f_b_count = 0
l_a_count = 0
b_a_count = 0

for n in xrange(N):
    s = raw_input()
    inner_ab_count += s.count('AB')
    if s[0] == 'B':
        if s[-1] == 'A': b_a_count += 1
        else: f_b_count += 1
    elif s[-1] == 'A': l_a_count += 1

if b_a_count <= 0: result = inner_ab_count + min([l_a_count, f_b_count])
elif l_a_count + f_b_count == 0: result = inner_ab_count + b_a_count-1
else: result = inner_ab_count + b_a_count + min([l_a_count,f_b_count])
print result

Submission status: Accepted

Solution code:
def countAB(s):
    c = 0
    for i in range(0, len(s), 2):
        if i+1 < len(s) and s[i] == 'A' and s[i+1] == 'B':
            c += 1
        elif i-1 >= 0 and s[i-1] == 'A' and s[i] == 'B':
            c += 1
    return c


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

head = []
tail = []
con = []
els = []

for i in range(n):
    h = s[i][0]
    t = s[i][-1]
    if h == 'B' and t == 'A':
        con.append(s[i])
    elif h == 'B':
        tail.append(s[i])
    elif t == 'A':
        head.append(s[i])
    else:
        els.append(s[i])

string = ''.join(els)
state = False
while True:
    if not state:
        if len(head) > 0:
            string += head.pop(0)
        elif len(con) > 0:
            string += con.pop(0)
        else: break
        state = True
    elif state:
        if len(con) > 0:
            string += con.pop(0)
        elif len(tail) > 0:
            string += tail.pop(0)
            state = False
        else: break

string = string + ''.join(head+tail+con)

print(countAB(string))

Submission status: Accepted

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

ct_a=0
ct_b=0
ct_ab=0
ct_ba=0

for i in range(N):
    if s[i][0]=='B' and s[i][-1]=='A':
        ct_ba+=1
    elif s[i][0]=='B':
        ct_b+=1
    elif s[i][-1]=='A':
        ct_a+=1
    for j in range(len(s[i])-1):
        if s[i][j]=='A' and s[i][j+1]=='B':
            ct_ab+=1

if ct_ba==0:
    print(ct_ab+min(ct_a, ct_b))
elif ct_a+ct_b>0:
    print(ct_ab+ct_ba+min(ct_a,ct_b))
else:
    print(ct_ab+ct_ba-1)

Submission status: Accepted

Solution code:
N=int(input())
start=0
end=0
r=0
cnt=0
for i in range(N):
    s=input()
    cnt+=s.count('AB')
    if s[0] == 'B':
        start+=1
    if s[-1] == 'A':
        end+=1
    if s[0] == 'B' and s[-1] == 'A':
        r+=1
if start == end and start == r and end > 0:
    cnt -=1
print(cnt+min(start,end))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
N = int(input())
S = [input() for i in range(N)]
c1, c2, c3, c = 0, 0, 0, 0
for s in S:
    if s[-1] == 'A' and s[0] == 'B':
        c1 += 1
    elif s[-1] != 'A' and s[0] == 'B':
        c2 += 1
    elif s[-1] == 'A' and s[0] != 'B':
        c3 += 1
    c += s.count('AB')

if c1 == 0:
    print(c + min(c2, c3))
elif c2 + c3 > 0:
    print(c + c1 + min(c2, c3))
else:
    print(c + c1 -1)

Submission status: Accepted

Solution code:
N = input()
s = []
flaga = 0
flagbs = 0
flagba = 0
Aend = 0
Bstart = 0
AB = 0
flaginit = 0
for i in range(N):
	s.append(raw_input())
for s2 in s:
	flaginit = 1
	flaga = 0
	flagbs = 0
	for c in s2:
		if flaginit == 1:
			if c =='A':
				flaga = 1
			elif c =='B':
				Bstart += 1
				flagbs = 1
			flaginit = 0
		else:
			if c == 'A':
				flaga = 1
			elif c =='B':
				if flaga == 1:
					AB += 1
				flaga = 0
			else:
				flaga = 0
	if flaga == 1:
		Aend += 1
		if flagbs == 0:
			flagba = 1
	else:
		if flagbs == 1:
			flagba = 1
if(flagba == 0 and Aend > 0):
	Aend -= 1
AB += min(Aend,Bstart,N-1)
print(AB)

Submission status: Accepted

Solution code:

# coding: utf-8

# In[17]:

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


# In[18]:

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:
ans = 0
if ab_cnt > 0:
    ans += ab_cnt - 1
    if b_cnt > 0:
        b_cnt -= 1
        ans += 1
    if a_cnt > 0:
        a_cnt -= 1
        ans += 1
ans += min(a_cnt, b_cnt)

"""
if max(a_cnt, b_cnt) == 0 and ab_cnt > 0:
    ab_cnt -= 1
elif min(a_cnt, b_cnt) > 0 and ab_cnt > 0:
    ab_cnt += 1
elif abs(a_cnt-b_cnt) == 0 and ab_cnt > 0:
    ab_cnt += 1
elif abs(a_cnt-b_cnt) > 0 and ab_cnt > 0:
    ab_cnt += 0
"""
    
#if ab_cnt < 0:
#    ab_cnt = 0
#ab_cnt = ab_cnt-1 if ab_cnt!=0 else ab_cnt
print('/'.join(S).count('AB') + ans)


# In[ ]:

Submission status: Accepted

Solution code:
n=int(input())
s=[input() for _ in range(n)]
isFinishA=[s[i][-1]=='A' for i in range(n)]
isStartB=[s[i][0]=='B' for i in range(n)]
ans=0
for si in s:
    wasA=False
    for sij in si:
        if sij=='B':
            if wasA:
                ans+=1
        wasA=(sij=='A')

fromBtoA=0
fromB=0
toA=0
for i in range(n):
    if isFinishA[i]:
        if isStartB[i]:
            fromBtoA+=1
        else:
            toA+=1
    else:
        if isStartB[i]:
            fromB+=1

if fromBtoA==0:
    ans+=min(fromB,toA)
else:
    if fromB+toA>0:
        ans+=fromBtoA+min(fromB,toA)
    if fromB+toA==0:
        ans+=fromBtoA-1
# print(fromB,toA,fromBtoA)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = []
ABcnt = 0
topABcnt = 0
topBbtmA = 0
topBbtmNO = 0
topNObtmA = 0
for _ in range(N):
  s = input()
  nowABcnt = s.count('AB')
  ABcnt += nowABcnt
  if s[0:2]=='AB':
    topABcnt += 1
  if s[0]=='B':
    if s[-1]=='A': topBbtmA += 1
    else: topBbtmNO += 1
  elif s[-1]=='A':
    topNObtmA += 1
  if nowABcnt!=0 or s[0]=='B' or s[-1]=='A': S.append(s)

ans = 0


ans += min(topBbtmNO, topNObtmA)
firstSurvivorCnt = max(topBbtmNO, topNObtmA) - ans

nikaisenGet = min(firstSurvivorCnt, topBbtmA)
ans += nikaisenGet

topBbtmA -= nikaisenGet
if ans == 0: ans += max(0, topBbtmA-1)
else: ans += topBbtmA #topBbtmAが生き残ってたら足す
#最後のtopBbtmAはペアを作れない

print(ans+ABcnt)

Submission status: Accepted

Solution code:
N = int(input())
s_list = [input() for _ in range(N)]
end_a_num = 0
start_b_num = 0
same_num = 0
ans = 0
for s in s_list:
    ab_num = s.count('AB')
    ans += ab_num
    if s[-1] == 'A':
        end_a_num+=1
    if s[0]=='B':
        start_b_num+=1
    if s[-1]=='A' and s[0]=='B':
        same_num+=1


ans+= min(end_a_num,start_b_num)
if end_a_num==start_b_num and end_a_num==same_num and end_a_num>0:
    ans-=1


print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = 0
B = 0
ans = 0
case = 0
for i in range(N):
  S = input()
  for j in range(len(S)-1):
    if S[j] == 'A' and S[j+1] == 'B':
      ans += 1
  if S[0] == 'B' and S[len(S)-1] == 'A':
    case += 1
  else:
    if S[0] == 'B':
      B += 1
    if S[len(S)-1] == 'A':
      A += 1
if case == 0:
  print(ans+min(A,B))
else:
  if A > 0 and B > 0:
    print(ans+case+1+min(A-1,B-1))
  elif A > 0 or B > 0:
    print(ans+case)
  else:
    print(ans+case-1)

Submission status: Accepted

Solution code:
n=int(input())

ans=0
ba=0
bstart=0
aend=0
for i in range(n):
  s=input()
  for j in range(len(s)):
    if s[j]=="A":
      if not j+1==len(s):
        if s[j+1]=="B":
          ans+=1
  
  if s[0]=="B" and s[-1]=="A":
    ba+=1
  else:
    if s[0]=="B":
      bstart+=1
    if s[-1]=="A":
      aend+=1
            
if ba==0:
  print(ans+min(bstart,aend))
else:
  if bstart>=1 and aend>=1:
    print(ans+ba-1+2+min(bstart-1,aend-1))
  else:
    print(ans+ba-1+max(min(1,bstart),min(1,aend)))

Submission status: Accepted

Solution code:
N=int(input())
lasta=0
headb=0
spec=0
cnt=0
for _ in range(N):
    s=str(input())
    cnt+=s.count("AB")
    if s[0]=="B" and s[-1]=="A":
        spec+=1
    elif s[-1]=="A":
        lasta+=1
    elif s[0]=="B":
        headb+=1
        
if abs(headb-lasta)>=spec:
    print(min(headb,lasta)+spec+cnt)   
elif lasta==0 and headb==0 and spec>0:
    print(spec-1+cnt)
elif lasta==0 and headb==0 and spec==0:
    print(cnt)
else:
    print(spec-abs(headb-lasta)+max(headb,lasta)+cnt)

Submission status: Accepted

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

for i in range(N):
    S = input()
    for j in range(len(S)-1):
        if S[j:j+2] == 'AB':
            c += 1
    if S[0] == 'B' and S[-1] == 'A':
        v += 1
        continue
    if S[0] == 'B':
        b += 1
    if S[-1] == 'A':
        a += 1
'''
if v >= 1:
    if a < b:
        a += 1
    else:
        b += 1
'''
if a >= 1 or b >= 1:
    print(c + v + min(a, b))
else:
    print(c + max(0, v-1))

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    S = [input() for _ in range(N)]
    AB_count = 0
    # 元から含まれているABの計算
    head_B_count = 0
    tail_A_count = 0
    B_and_A_count = 0
    for si in S:
        # print(si.count('AB'))
        AB_count += si.count('AB')
        # print(list(si)[0], list(si)[-1])
        list_si = list(si)
        if list_si[0] == 'B' and list_si[-1] == 'A':
            B_and_A_count += 1
            pass
        elif list_si[0] == 'B':
            head_B_count += 1
        elif list_si[-1] == 'A':
            tail_A_count += 1
    if B_and_A_count > 0:
        AB_count += B_and_A_count - 1
        if head_B_count > 0:
            AB_count += 1
            head_B_count -= 1
        if tail_A_count > 0:
            AB_count += 1
            tail_A_count -= 1
    AB_count += min(head_B_count, tail_A_count)
    print(AB_count)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
N= int(input())

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

if(b==0 or a==0): print(ans) 
elif(k>0 and k==a and b==k): print(ans+k-1)
else: print(ans + min(a,b,N-1))

Submission status: Accepted

Solution code:
N = int(input())
AB_number = 0
ab_cnt =0
a_cnt = 0
b_cnt = 0
for _ in range(N):
    s_i = input()
    AB_number += s_i.count("AB")
    if s_i[0] == "B" and s_i[-1] == "A":
        ab_cnt += 1
    elif s_i[-1] == "A":
        a_cnt += 1
    elif s_i[0] == "B":
        b_cnt += 1

if ab_cnt== 0:
    print(AB_number+min(a_cnt,b_cnt))
elif a_cnt != b_cnt:
    print(AB_number+(ab_cnt-1)+1+min(a_cnt,b_cnt))
elif a_cnt==0:
    print(AB_number+(ab_cnt-1)+min(a_cnt,b_cnt))
else:
    print(AB_number+(ab_cnt-1)+1+min(a_cnt,b_cnt))

Submission status: Accepted

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

c = 0
a = 0
b = 0
ab = 0

for i in range(0, n):
    for j in range(1, len(s[i])):
        if s[i][j-1:j+1] == "AB":
            c += 1
    if s[i][-1] == "A" and s[i][0] == "B":
        ab += 1
    else: 
        if s[i][0] == "B":
            b += 1
        if s[i][-1] == "A":
            a += 1
            
s = c

if ab > 0:
    s += ab - 1
    if a > 0:
        s += 1
        a -= 1
    if b > 0:
        s += 1
        b -= 1

s += min(a, b)

print(s)

Submission status: Accepted

Solution code:
N = int(input())
end_A_only = 0
start_B_only = 0
both = 0
count = 0
for i in range(N):
    s = input()
    count += s.count("AB")
    if s[-1] == "A" and s[0] == "B":
        both += 1
    elif s[-1] == "A":
        end_A_only += 1
    elif s[0] == "B":
        start_B_only += 1
    else:
        pass

if both == 0:
    count += min(end_A_only, start_B_only)

else:
    if end_A_only == 0 and start_B_only == 0:
        count += both - 1
    elif end_A_only == 0 or start_B_only == 0:
        count += both
    else:
        count += both + 1
        count += min(end_A_only - 1, start_B_only - 1)


print(count)

Submission status: Accepted

Solution code:
N=int(input())
lasta=0
headb=0
spec=0
cnt=0
for _ in range(N):
    s=str(input())
    for i in range(len(s)-1):
        if s[i:i+2]=="AB":
            cnt+=1
    if s[0]=="B" and s[-1]=="A":
        spec+=1
    elif s[-1]=="A":
        lasta+=1
    elif s[0]=="B":
        headb+=1
        
if abs(headb-lasta)>=spec:
    print(min(headb,lasta)+spec+cnt)   
elif lasta==0 and headb==0 and spec>0:
    print(spec-1+cnt)
elif lasta==0 and headb==0 and spec==0:
    print(cnt)
else:
    print(spec-abs(headb-lasta)+max(headb,lasta)+cnt)

Submission status: Accepted

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

b = b - ba
a = a - ba

ans = ab #ABが普通に含まれた数
if ba > 0:
    ba_joind = ba - 1 #B*Aを連結して生じるAB
    if b > 0:
        b = b - 1
        ba_joind = ba_joind + 1
    if a > 0:
        a = a - 1
        ba_joind = ba_joind + 1
    ans = ans + ba_joind
if b > 0 and a > 0:
    ans = ans + min(a, b)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())

a = 0
b = 0
c = 0
ans = 0

for _ in range(N):
    s = input()
    flag = False
    for i in range(len(s)):
        if (flag == True) and (s[i] == "B"):
            ans += 1
            flag = False
        elif (s[i] == "A"):
            flag = True
        else:
            flag = False
    if (s[0] == "B" and s[-1] == "A"):
        c += 1
    elif (s[0] == "B"):
        b += 1
    elif (s[-1] == "A"):
        a += 1
if c > 0:
    ans += c - 1
    c = 1
    if (a > 0 or b > 0):
        ans += 1
print(ans + min(a, b))

Submission status: Accepted

Solution code:
from sys import stdin
    
def calc(s):
    lastA = 0
    firstB = 0
    both = 0
    interAB = 0
    for _s in s:
        if _s[0] == 'B' and _s[-1] == 'A':
            both += 1
        else:
            if _s[0] == 'B':
                firstB += 1
            if _s[-1] == 'A':
                lastA += 1
        
        interAB += _s.count('AB')

    if lastA == 0 and firstB == 0:
        both = max(both-1,0)
    return min(lastA + both, firstB + both) + interAB

def main():
    n = stdin.readline().rstrip()
    s = [x.rstrip() for x in stdin.readlines()]
    ans = calc(s)
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
#-------------------------------------------------------------------
import sys
def p(*a):
  s=" ".join(map(str,a))
  #print(s)
  sys.stderr.write(s+"\n")
#-------------------------------------------------------------------

N = int(input())

ans=a=b=ba=ab=0

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

ans+=ab
ans+=max(0,ba-1)

#if (abs(a-b)>0)and(ba>0): ans+=1
if ba>0:
	if b>0:
		ans+=1
		b-=1
	if a>0:
		ans+=1
		a-=1

ans+=min(b,a)


print(ans)


p(a,b,ba,ab)

Submission status: Accepted

Solution code:
N = int(input())
s = [input() for i in range(N)]
abc = sum([e.count("AB") for e in s]) # 各文字列のAB出現回数
bstart, aend = 0, 0
B_A = 0
for e in s:
    if e[0] == "B":
        bstart += 1
    if e[-1] == "A":
        aend += 1
    if e[0] == "B" and e[-1] == "A":
        B_A += 1
makedB_A = min(bstart-B_A, aend-B_A)
ans = 0

if bstart == 0 and aend == 0:
    ans = abc
elif bstart == aend:
    if makedB_A == 0:
        ans = abc + bstart - 1 
    else:
        ans = abc + bstart
else:
    ans = abc + min(bstart, aend)

    
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = []
for i in range(N):
    s.append(input())
A = 0
B = 0
BA = 0
inAB = 0
for i in range(N):
    if s[i][-1] == "A" and s[i][0] == "B":
        BA += 1
    elif s[i][-1] == "A":
        A += 1
    elif s[i][0] == "B":
        B += 1
    inAB += s[i].count("AB")

if A == B and A == 0 and BA != 0: BA -= 1
print(min(A+BA,B+BA)+inAB)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
stlist = []
bf = 0
al = 0
ab = 0
ba = 0
#test = ["BEWPVCRWH","ZZNQYIJX","BAVREA", "PA", "HJMYITE0X","BG","BP","QABZ","PRA"]
for i in range(N):
    tmp = str(input())
    ab += tmp.count("AB")
    if tmp[0] == 'B' and tmp[-1] == 'A':
        ba += 1
    elif tmp[0] =='B':
        bf+=1
    elif tmp[-1] =='A':
        al+=1
if al+bf+ba==0:
    print(ab)
elif al == 0 and bf ==0:
    print(ba-1+ab)
elif al * bf ==0:
    print(max(min(al-1, bf-1), 0) + ba + ab)
else:
    print(max(min(al-1, bf-1), 0) + ba +1 + ab)

Submission status: Accepted

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


a = 0
b = 0
c = 0
d = 0
for s in ss:

    d += 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 c > 0:
    d+= c-1
    if a > 0 :
        d+=1
        a -= 1
    if b > 0 :
        d+=1
        b -= 1

print(d + min(a,b))

Submission status: Accepted

Solution code:
n = int(input())
firsts = 0
lasts = 0
doubles = 0
inners = 0
for i in range(n):
    s = input()
    first = 1 if (s[0] == "B" and s[-1] != "A") else 0
    last = 1 if (s[-1] == "A" and s[0] != "B") else 0
    double = 1 if (s[0] == "B" and s[-1] == "A") else 0
    inner = s.count("AB")
    # ss += s
    firsts += first
    lasts += last
    doubles += double
    inners += inner
if doubles == 0 and firsts == 0 and lasts == 0:
    print(inners)
elif firsts == 0 and lasts == 0:
    print(inners + doubles - 1)
# elif firsts == 0 or lasts == 0:
#     print(inners + doubles)
else:
    print(inners + doubles + min(firsts, lasts))

Submission status: Accepted

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)
# print(a_last, b_start, both, ans, diff)
if both>=1:
    ans+=both-1
    if a_last>=1:
        ans+=1
        a_last-=1
    if b_start>=1:
        ans+=1
        b_start-=1
ans+=min(a_last,b_start)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())

cnt = 0
a_flag = 0
b_flag = 0
ab_flag = 0

s = [0]*n
for i in range(n):
    s[i] = input()

    for j in range(len(s[i])-1):
        if s[i][j:j+2] == 'AB':
            cnt += 1

    if s[i][0] == 'B' and s[i][-1] != 'A':
        b_flag += 1
    elif s[i][-1] == 'A' and s[i][0] != 'B':
        a_flag += 1
    elif s[i][0] == 'B' and s[i][-1] == 'A':
        ab_flag += 1

if ab_flag != 0:
    if a_flag == 0 and b_flag == 0:
        print(cnt + ab_flag - 1)
    elif a_flag>=1 and b_flag >= 1:
        print(cnt + ab_flag + 1 + min(a_flag - 1, b_flag - 1))
    else:
        print(cnt + ab_flag) 
else:
    print(cnt + min(a_flag, b_flag))

Submission status: Accepted

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

Submission status: Accepted

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

counter = 0
begin_b = []
end_a = []
begin_b_and_end_a = []
for i in range(n):
    counter += s[i].count('AB')
    if s[i][0] == 'B':
        begin_b.append(i)
    if s[i][-1] == 'A':
        end_a.append(i)
    if s[i][0] == 'B' and s[i][-1] == 'A':
        begin_b_and_end_a.append(i)

if len(begin_b) == len(begin_b_and_end_a) and len(begin_b_and_end_a) == len(end_a) and len(end_a) > 0:
    print(counter + min(len(begin_b), len(end_a)) - 1)
else:
    print(counter + min(len(begin_b), len(end_a)))

Submission status: Accepted

Solution code:
N = int(input())

a_end = 0
b_start = 0
ab = 0
zz = 0
for n in range(N):
    s = input()
    ab = ab + s.count('AB')
    if s[-1] == 'A':
        a_end = a_end + 1
    if s[0] == 'B':
        b_start = b_start + 1
    if s[-1] != 'A' and s[0] != 'B':
        zz = zz + 1

print(ab + max(min(a_end, b_start, N - 1 - zz), 0))

Submission status: Accepted

Solution code:
N = int(input())

strings = []
for _ in range(N):
    strings.append(input())

cnt = 0
cnt_A = cnt_B = 0
flag = False
for s in strings:
    for c1, c2 in zip(s, s[1:]):
        if c1 == 'A' and c2 == 'B':
            cnt += 1

    if s[0] == 'B':
        cnt_B += 1
        if s[-1] != 'A':
            flag = True
    if s[-1] == 'A':
        cnt_A += 1
        if s[0] != 'B':
            flag = True

cnt += min(cnt_A, cnt_B)
if cnt_A == 0 and cnt_B == 0:
    flag = True
print(cnt if flag else cnt - 1)

Submission status: Accepted

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

Submission status: Accepted

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'):
        if substr.endswith('A'):
            counter['b_to_a'] += 1
        else:
            counter['begin_b'] += 1
    else:
        if substr.endswith('A'):
            counter['end_a'] += 1

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

print(total)

Submission status: Accepted

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

cnt = 0
cntA = 0
cntB = 0
cntAB = 0

for s in S :
    for i in range(1, len(s)) :
        if s[i - 1] =='A' and s[i] == 'B':
            cnt += 1
    if s[0] == 'B' and s[len(s) - 1] == 'A':
        cntAB += 1
    elif s[0] == 'B' :
        cntB += 1
    elif s[len(s) - 1] == 'A' :
        cntA += 1

ans = min(cntA, cntB)
if cntAB >= 2 :
    ans += (cntAB - 1)
if cntAB >= 1 and max(cntA, cntB) != 0:
    ans += 1

'''
if max(cntA, cntB) == 0:
    ans = cntAB - 1
else :
    ans += cntAB
'''
if ans == len(S) :
    ans -= 1

print(cnt + ans)

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    S = [input() for i in range(N)]
    ans = sum([s.count('AB') for s in S])
    a1 = len([1 for s in S if s[-1] == 'A'])
    b1 = len([1 for s in S if s[0] == 'B'])
    ab1 = len([1 for s in S if s[-1] == 'A' and s[0] == 'B'])

    #print('ans,a1,b1,ab1',ans,a1,b1,ab1)
    if a1 > b1:
        return ans + b1
    elif a1 < b1:
        return ans + a1

    if a1 == ab1 and ab1 > 0:
        return ans + ab1 - 1

    return ans + a1

print(solve())

Submission status: Accepted

Solution code:
import re
n = int(input())
s = []
compiled = re.compile(r"AB")

pre = 0
xa=0
bx=0
ba=0
for i in range(n):
    one = input()
    pre+=len(compiled.findall(one))
    f=one[0]
    l=one[-1]


    if f=="B" and l=="A":
        ba+=1
    elif f=="B" and l!="A":
        bx+=1
    elif f!="B" and l=="A":
        xa+=1

#print(ba,bx,xa,pre)
cnt=0
if ba>=1:
    cnt+=ba-1
    if xa>=1:
        xa-=1
        cnt+=1
    
    if bx>=1:
        bx-=1
        cnt+=1

cnt += xa if xa<bx else bx
print(cnt+pre)

Submission status: Accepted

Solution code:

n = int(input())
s = []

for i in range(n):
    s.append(input())

a = 0
b = 0
ab = 0
ba = 0
for i in range(n):
    if (s[i][-1].count("A") and s[i][0].count("B")):
        ba += 1
    else:
        a += s[i][-1].count("A")
        b += s[i][0].count("B")
    ab += s[i].count("AB")

if ba != 0:
    ab += ba - 1
    if a > b:
        b += 1
    elif b > a:
        a += 1
    elif a == b and a >= 1:
        a += 1
        b += 1

print(ab + min(a,b))