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:
import math
N = int(input())
l = []
for i in range(N):
   l.append(input())

default = sum(['AB' in i for i in l])

#only末尾Aの数
a = sum([i[-1]=='A' and i[0]!='B' for i in l])
#only先頭Bの数
b = sum([i[0]=='B' and i[-1]!='A' for i in l])
#先頭Bかつ末尾Aの数
ab = sum([i[0]=='B' and i[-1]=='A' for i in l])

# print("default = ", str(default))
# print("a = ", str(a))
# print("b = ", str(b))
# print("ab = ", str(ab))

if a == b:
    if ab > a:
        num = 2 * a + ab - a -1
    elif ab == a:
        num = 2 * a
    elif ab < a:
        num = 2 * ab + a - ab
else:
    min = min(a, b)
    max = max(a, b)
    gap = abs(a-b)
    if ab <= min:
        num = ab * 2 + min - ab
    elif ab > min:
        num = min * 2 + ab - min - 1

print(num + default)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
topb = 0
taila = 0
both = 0
cnt = 0
for _ in range(N):
    s = input()
    cnt +=s.count("AB")

    if s[0] == "B" and s[-1] == "A":
        both += 1
    elif s[0] == "B":
        topb += 1
    elif s[-1] == "A":
        taila += 1

con_cnt_min,con_cnt_max = min(topb,taila),max(topb,taila)
use_both = min(both,con_cnt_min+con_cnt_max)
cnt += use_both
both -= use_both

print(cnt + con_cnt_min + both)

Submission status: Wrong Answer

Solution code:
n=int(input())
string_list=[input() for i in range(n)]
new_list = {}
target_chr = "AB"
count = 0
left_b_count = 0
right_a_count = 0
l_r_count = 0
none_count = 0
for string in string_list:
    if string.count(target_chr) > 0 and (string[0] != "B" or string[-1] != "A"):
        count += string.count(target_chr)
        none_count += 1
        continue
    if string[0] == "B" and string[-1] == "A":
        count += string.count(target_chr)
        none_count += 1
        l_r_count += 1
        continue     
    if string[0] == "B":
        left_b_count +=1
        count += string.count(target_chr)
        none_count += 1
        continue
    if string[-1] == "A":
        right_a_count += 1
        count += string.count(target_chr)
        none_count += 1
        continue
if l_r_count > 0:
    count += l_r_count + 1
    left_b_count -= 1
    right_a_count -= 1

if left_b_count > right_a_count:
    print(count + right_a_count)
else:
    print(count + left_b_count)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
counter = 0
counter_AB = 0
counter_A = 0
counter_B = 0

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

for n in range(N):
    tmp = s[n]
    counter += tmp.count("AB")
    
    if tmp[0] == "B" and tmp[len(tmp)-1] == "A":
        counter_AB += 1

    elif tmp[0] == "B":
        counter_B += 1
    
    elif tmp[len(tmp)-1] == "A":
        counter_A += 1



counter_sort = [counter_A, counter_B]

print(counter + counter_sort[0] + counter_AB)

Submission status: Wrong Answer

Solution code:
import sys 

input()
bsn = 0
aen = 0
cen = 0
t = 0
for line in sys.stdin:
    st = line.strip()
    t += st.count("AB")
    if st[0] == "B" and st[-1] == "A":
        cen += 1
    elif st[0] == "B":
        bsn += 1
    elif st[-1] == "A":
        aen += 1

if aen != 0:
    if bsn != 0:
        if cen != 0:
            x = min(bsn-1, aen-1)
            print(t+cen+1+x)
        else:
            x = min(bsn, aen)
            print(t+x)
    else:
        print(t+cen)
else:
    if bsn != 0:
        print(t+cen)
    else:
        print(t+cen-1)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3

n = int(input())

cnt=0
cnt_a=0
cnt_b=0
cnt_d=0

for i in range(n):
    s=input()
    cnt += s.count("AB")
    if s[-1]=='A':
        cnt_a+=1
    if s[0]=='B':
        cnt_b+=1
    if s[-1]=='A' and s[0]=='B':
        cnt_d+=1

cnt += min(cnt_a,cnt_b)
if cnt_d == max(cnt_a,cnt_b):
    cnt-=1

print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())

cnt = 0
a = {}
b = {}
for i in range(N):
    S = input()
    cnt += S.count('AB')
    if S.startswith('B'):
        b[i] = 'B'
    if S.endswith('A'):
        a[i] = 'A'

print(min(len(a.values()), len(b.values())) + cnt)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[0]*n
for i in range(n):
    s[i]=input()
sab=0
cntAB=0
cntA=0
cntB=0
cntc=0
for i in range(n):
    if s[i][0]=="B":
        c1=1
    else:
        c1=0
    if s[i][len(s[i])-1]=="A":
        c2=1
    else:
        c2=0
    if c1==1 and c2==1:
        cntAB+=1
    elif c1==1:
        cntA+=1
    elif c2==1:
        cntB+=1
    else:
        cntc+=1
    for j in range(len(s[i])-1):
        if s[i][j]=="A" and s[i][j+1]=="B":
            sab+=1
if cntAB+cntc==n:
    cntAB-=1
print(sab+cntAB+min(cntA,cntB))

Submission status: Wrong Answer

Solution code:
n=int(input())

A_count=0
B_count=0
BA_count=0
include_count=0

for i in range(n):
    moji=input()
    if 'AB' in moji:
        include_count+=1
    moji_line=list(moji)
    if moji_line[0]=='B' and moji_line[-1]=='A':
        BA_count+=1
    elif moji_line[0]=='B':
        B_count+=1
    elif moji_line[-1]=='A':
        A_count+=1
    # pair=[moji,moji_line[0],moji_line[-1]]
    # print(pair)

s=include_count
if BA_count==0:
    s+=min(A_count,B_count)

else:
    s+=max(BA_count-1,0)
    if min(A_count,B_count)>=1:
        s+=min(A_count,B_count)+1
    elif A_count==0 and B_count==0:
        s+=0
    else:
        s+=1

print(s)

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = 0
abcount = 0
acount = 0
bcount = 0

for i in range(N):
	s = input()
	cnt += s.count('AB')
	if s.startswith('B') and s.endswith('A'):
		abcount += 1
	if s.startswith('B'):
		bcount += 1
	if s.endswith('A'):
		acount += 1

if abcount == acount and abcount == bcount:
	print(cnt + abcount -1)
else:
	print(cnt + min(acount, bcount))

Submission status: Wrong Answer

Solution code:
N = int(input())

n_fin_is_A = 0
n_ini_is_B = 0
n_each_ab = 0

for n in range(N):
    S = input()
    n_each_ab += S.count('AB')
    n_fin_is_A += int(S[-1]=='A')
    n_ini_is_B += int(S[0]=='B')

_min = min(n_fin_is_A, n_ini_is_B)
if _min > N-1:
    _min + N-1

print(n_each_ab + _min)

Submission status: Wrong Answer

Solution code:
n = int(input())

cnt = 0
a_cnt = 0
b_cnt = 0
ab_cnt = 0
for i in range(n):
  s = input()
  for l in range(len(s)-1):
    if s[l] == 'A' and s[l+1] == 'B':
      cnt = cnt +1
  if s[-1] == 'A':
    a_cnt = a_cnt +1
  if s[0] == 'B':
    b_cnt = b_cnt +1
  if s[-1] == 'A' and s[0] == 'B':
    ab_cnt = ab_cnt +1

tmp = min(a_cnt, b_cnt)
if a_cnt == ab_cnt and b_cnt == ab_cnt:
  tmp =0
#print (a_cnt)
#print (b_cnt)
#print (ab_cnt)
#print (cnt)
print(cnt + tmp)

Submission status: Wrong Answer

Solution code:
a=input()
a=int(a)
count=0
ap=0
bp=0
abc=0
for j in range(a):
    app=0
    bpp=0
    switch=0
    b=input()
    ofset=0
    for i in b:
        if i=="B" and ofset==0:
            bp+=1
            bpp+=1
        elif i=="A":
            switch+=1
        elif i=="B" and switch==1:
            count+=1
            switch=0
        else:
            switch=0
        ofset+=1
    if switch==1:
        ap+=1
        app=1
    if app==1 and bpp==1:
        abc+=1
        ap-=1
        bp-=1
pp=a-1
if ap>bp:
    count+=bp
    bp=0
    ap-=bp
    pp-=bp
else:
    count+=ap
    ap=0
    bp=0
    pp-=ap
if abc>0:
    count+=abc-1
    pp-=abc-1
    if ap>0 or bp>0:
        if pp>0:
            count+=1
print(count)

Submission status: Wrong Answer

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

count = 0
a_count = 0
b_count = 0
for i in range(len(s_list)):
    count += s_list[i].count("AB")
    if s_list[i][-1] == "A":
        a_count += 1
    if s_list[i][0] == "B":
        b_count += 1
    if s_list[i][-1] == "A" and s_list[i][0] == "B":
        a_count -= 1
        b_count -= 1

if a_count == N and b_count == N :
    print(count + a_count - 1)
elif a_count > b_count :
    print(count + b_count)
else :
    print(count + a_count)

Submission status: Wrong Answer

Solution code:
n=int(input())
c1=c2=c3=0
c=0
for i in range(n):
  s=input()
  c+=s.count('AB')

  if s[0]=='B' and s[-1]=='A':
    c3+=1
  elif s[0]=='B':
    c1+=1
  elif s[-1]=='A':
    c2+=1

cc=c
cc+=max(0,c3-1)
if c1<c2:
  c2-=c1
  cc+=c1
  if c2>0 and c3>0:
    cc+=1
elif c1==c2:
  cc+=c1
else:
  c1-=c2
  cc+=c2
  if c1>0 and c3>0:
    cc+=1

if c3>max(c1,c2):
  if c1<c2:
    c+=c1*2
    c3-=c1
    c+=c3
  elif c1==c2:
    c+=c1*2
    c3-=c1
    c+=max(0,c3-1)
  else:
    c+=c2*2
    c3-=c2
    c+=c3
elif c3>=min(c1,c2) and c3<=max(c1,c2):
  if c1<c2:
    c+=c1*2
    c2-=c1
    c3-=c1
    c+=c3
  else:
    c+=c2*2
    c1-=c2
    c3-=c2
    c+=c3
else:
  c+=c3*2
  c1-=c3
  c2-=c3
  c+=min(c1,c2)

print(max(c,cc))

Submission status: Wrong Answer

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)]
cnt=[isFinishA.count(True),isStartB.count(True)]
ans=min(cnt)

for si in s:
    wasA=False
    for sij in si:
        if sij=='B':
            if wasA:
                ans+=1
        wasA=(sij=='A')

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

if cnt[0]==cnt[1]==fromBtoA:
    ans-=1
print(ans)

Submission status: Wrong Answer

Solution code:
# coding:utf-8

if __name__=="__main__":
  N = int(input())
  s = []
  a,b,ba=0,0,0
  count = 0
  for i in range(N):
      s.append(input())
      count += s.count('AB')
      if s[i][0]!='B' and s[i][-1]=='A': a+=1
      if s[i][0]=='B' and s[i][-1]!='A': b+=1
      if s[i][0]=='B' and s[i][-1]=='A': ba+=1
  if ba == 0:
      print(count+min(a,b))
  elif min(a,b)==0:
      print(count+ba-1)
  else:
      print(count+ba+min(a,b))

Submission status: Wrong Answer

Solution code:
N = int(input())
 
moji_list = []
A_count = 0
B_count = 0
AB_count = 0
B_A_count = 0

if N == 1:
    moji = input()
    print(moji.count('AB'))

else:
    for i in range(N):
        moji = input()
        if moji[-1] == 'A' and moji[0] == 'B':
            B_A_count += 1
        elif moji[0] == 'B':
            B_count += 1
        elif moji[-1] == 'A':
            A_count += 1
        
        AB_count += moji.count('AB')

    if B_A_count == 0:
        if A_count >= B_count:
            print(AB_count+B_count)
        else:
            print(AB_count+A_count)
    
    else:
        if A_count > B_count and A_count-B_count > B_A_count:
            print(AB_count+B_count+B_A_count)
        elif A_count > B_count and A_count-B_count <= B_A_count:
            print(AB_count+B_count+B_A_count)
        elif A_count < B_count and B_count-A_count > B_A_count:
            print(AB_count+A_count+B_A_count)
        elif A_count < B_count and B_count-A_count <= B_A_count:
            print(AB_count+A_count+B_A_count)

Submission status: Wrong Answer

Solution code:
n = int(input())
S = []
for i in range(n):
    s = str(input())
    S.append(s)
    
ans = 0
countA = 0
countB = 0
countBA = 0
for s in S:
    if s[0] == 'B' and s[len(s)-1] == 'A':
        countBA += 1
        
    elif s[len(s)-1] == 'A':
        countA += 1
        
    elif s[0] == 'B':
        countB += 1
        
    for i in range(len(s) - 1):
        if s[i] == 'A' and s[i+1] == 'B':
            ans += 1
# print(countA, countB, countBA)
# print(ans)

if abs(countA - countB) > 0:
    ans = min(countA, countB) + countBA
else:
    ans = min(countA, countB) + countBA - 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ans = 0
count = [0, 0, 0]
for s in S:
    ans += s.count('AB')
    if s[0] + s[-1] == 'BA':
        count[2] += 1
    elif s[0] == 'B':
        count[1] += 1
    elif s[-1] == 'A':
        count[0] += 1
m = min(count)
count = [_ - m for _ in count]
ans += m * 2
count[0], count[1] = sorted(count[:2])
if count[0]:
    ans += count[0]
else:
    if count[1]:
        ans += count[2]
    else:
        ans += count[2] - 1
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import Counter
from collections import deque
from functools import reduce
from pprint import pprint
# import statistics
import bisect
import copy
import fractions
import math
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())
def IS(): return input()
def C(x): return Counter(x)
def GCD_LIST(numbers):
    return reduce(fractions.gcd, numbers)
def LCM_LIST(numbers):
    return reduce(LCM, numbers)
def LCM(m, n):
    return (m * n // fractions.gcd(m, n))
def unite(x, y):
    # それぞれのノードの根を求める
    x = root(x)
    y = root(y)
    if x == y:
        return
    # node[x]の根をyに変更する
    node[x] = y
def same(x,y): return bool(root(x) == root(y))
def root(x):
    if node[x] == x:  # xが根の場合
        return x
    else:
        node[x] = root(node[x])  # 経路圧縮
        return node[x]
def dfs(v):
    # ノードに訪れた
    visited[v] = True
    for v2 in range(n):
        if graph[v][v2] == False:  # そもそもvとv2が辺でつながっていない
            continue
        if visited[v2] == True:  # もう見た
            continue
        dfs(v2)

n = II()
s = [IS() for _ in range(n)]
cnt = 0
sentou_b = 0
ushiro_a = 0
ab = 0
for i in s:
    cnt += i.count('AB')
    if i[0] == 'B' and i[-1] == 'A':
        ab += 1
    else:
        if i[0] == 'B':
            sentou_b += 1
        if i[-1] == 'A':
            ushiro_a += 1
# print(cnt)
# print(sentou_b)
# print(ushiro_a)
# print(ab)
# print('===')
if ab > 0 and abs(sentou_b - ushiro_a) >= 1:
    print(cnt+min(sentou_b, ushiro_a)+1)
else:
    print(cnt+min(sentou_b, ushiro_a))

Submission status: Wrong Answer

Solution code:
import re
n = int(input())
lst = []
ab = 0
a = 0
b = 0
for i in range(n):
  x = input()
  lst.append(x)
  if "AB" in x:
    ab += len(re.findall('AB', x))
  if x[0] == "B":
    a += 1
  if x[-1] == "A":
    b += 1
if a == b:
  c = a-1
else:
  c = min(a,b)
print(ab+c)

Submission status: Wrong Answer

Solution code:
count = 0
a = 0
b = 0
ba = 0
N = int(input())
for x in range(N):
  s = input()
  if s[0] == 'B':
    a += 1
  if s[-1] == 'A':
    b += 1
  if s[0] == 'B' and s[-1] == 'A': 
    ba += 1
  target = 'AB'
  index = -1
  while True:
    index = s.find(target, index + 1)
    if index == -1:
        break
    count += 1
if a > b :
  count += b
elif a <= b:
  count += a
elif a == b and a == ba:
  count += a - 1
print(count)

Submission status: Wrong Answer

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

A = 0
B = 0
AB = 0

cnt = 0 

for _ in range(N):
    Si = input()
    cnt += Si.count('AB')
    if Si[0] == 'B' and Si[-1] == 'A':
        AB += 1
    elif Si[0] == 'B':
        B += 1
    elif Si[-1] == 'A':
        A += 1

if AB > 1:
    cnt += AB -2 
    if A > 0:
        cnt += 1
        A -= 1
    if B > 0:
        cnt += 1
        B -= 1
    if A > B :
        cnt += B
    else:
        cnt += A
else: 
    if A > B :
        cnt += B
    else:
        cnt += A
print(cnt)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

N = int(input())

A = []

for n in range(N):
    chars = np.array(list(input()))
    A.append(chars)

#print(A[1][2])

A_cnt = 0
B_cnt = 0
AsBe = 0 # A start, B end
AB_cnt = 0

for n in range(N):
    if A[n][0] == "B":
        B_cnt += 1

    if A[n][-1] == "A":
        A_cnt += 1

    if A[n][-1] == "A" and A[n][0] == "B":
        AsBe += 1
        A_cnt -= 1
        B_cnt -= 1

    for i in range(len(A[n])-1):
        if A[n][i] == "A":
            if A[n][i+1] == "B":
                AB_cnt += 1

if A_cnt > 0:
    a = 1
    A_cnt -= 1
else:
    a = 0

if B_cnt > 0:
    b = 1
    B_cnt -= 1
else:
    b = 0

print(AB_cnt + (AsBe-1) + a + b + min(A_cnt,B_cnt))

Submission status: Wrong Answer

Solution code:
n=int(input())
god=[]
F=0
B=0
both=0
cnt=0
Key=True
s=([input() for i in range(n)])
for i in range(n):
	cnt+=s[i].count('AB')
	if s[i][0]=='B' and s[i][len(s[i])-1]=='A':
		both+=1
	elif s[i][0]=='B':
		F+=1
	elif s[i][len(s[i])-1]=='A':
		B+=1
#print(both)
#print(F)
#print(B)
#print(cnt)

if  0<F and 0<B:
	if both<=min(F,B):
		cnt+=both*2+min(F,B)-both
	elif min(F,B)<both:
		cnt+=min(F,B)*2+both-min(F,B)
elif F==0 and B==0:
	cnt+=both-1
else :
	cnt+=both
		
print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
for i in range(n):
    s.append(input())
ans = 0
last = 0
start = 0
a = 0
b = 0
for i in range(n):
    ans += s[i].count('AB')
    list = s[i]
    if list[-1] == 'A' and list[0] != 'B':
        last += 1
        a += 1
    elif list[0] == 'B' and list[-1] != 'A':
        start += 1
        b += 1
    elif list[-1] == 'A' and list[0] == 'B':
        last += 1
        start += 1
    # print(ans, last, start)
ans += min(last, start)
if a == 0 and b == 0:
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
A=[]
edges=[]
num_ab=0
comb=0

for i in range(N):
    item=input()
    left=0
    right=0
    A.append(item)
    
    #internal AB
    for i in range(len(item)-1): 
        if item[i]=='A' and item[i+1]=='B':
            num_ab+=1


    if item[0]=='A':
        left=1
    elif item[0]=='B':
        left=2
    if item[-1]=='A':
        right=1
    elif item[-1]=='B':
        right=2            
    if left>0 or right >0:
        edges.append([left,right])    
        
for a,i in enumerate(edges):
    if i[0]==2:
        for b,j in enumerate(edges):
            if a!=b and j[1]==1:
                comb+=1
                i[0]=0
                j[1]=0   
                
ans=num_ab+comb
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
numA=0
numB=0
numBA=0

def check(s):
    if not "AB" in s:
        return 0
    cnt=0
    for a,b in zip(s[:-1],s[1:]):
        if a=="A" and b=="B":
            cnt+=1
    return cnt

ans=0
for i in range(n):
    s=input()
    ans+=check(s)
    if s[0]=="B" and s[-1]=="A":
        numBA+=1
    elif s[0]=="B":
        numB+=1
    elif s[-1]=="A":
        numA+=1
    
ans2=0

for i in range(numBA):
    if numA<numB:
        numA+=1
    elif numA>numB:
        numB+=1
    else:
        numA+=1
        numB+=1

print(ans+min(numA,numB))

Submission status: Wrong Answer

Solution code:
#https://atcoder.jp/contests/diverta2019/tasks/diverta2019_a
# -*- coding: utf-8 -*-

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

cnt = 0
A = 0
B = 0
AB = 0

for i in s:
        if "AB" in i:
                cnt += 1
        if i[len(i)-1] == "A" and i[0] != "B":
                A += 1
        if i[len(i)-1] != "A" and i[0] == "B":
                B += 1
        if i[len(i)-1] == "A" and i[0] == "B":
                AB += 1

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

print(ans)

Submission status: Wrong Answer

Solution code:
import math
N = int(input())
l = []
for i in range(N):
   l.append(input())

default = sum(['AB' in i for i in l])

#only末尾Aの数
a = sum([i[-1]=='A' and i[0]!='B' for i in l])
#only先頭Bの数
b = sum([i[0]=='B' and i[-1]!='A' for i in l])
#先頭Bかつ末尾Aの数
ab = sum([i[0]=='B' and i[-1]=='A' for i in l])

# print("default = ", str(default))
# print("a = ", str(a))
# print("b = ", str(b))
# print("ab = ", str(ab))

if a == b:
    if ab > a:
        num = 2 * a + ab - a -1
    elif ab == a:
        num = 2 * a
    elif ab < a:
        num = 2 * ab + a - ab
else:
    min = min(a, b)
    max = max(a, b)
    gap = abs(a-b)
    if ab <= min:
        print("!!")
        num = ab * 2 + gap - ab
    elif ab > min:
        print("!!!")
        num = min * 2 + ab - min - 1

print(num + default)

Submission status: Wrong Answer

Solution code:
N = int(input())
B_start_cnt = 0
A_end_cnt = 0
AB_cnt = 0
BA_cnt = 0
for i in range(N):
    s = input()
    if s[0] == "B" and s[-1] == "A":
        BA_cnt += 1
    if s[0] == "B":
        B_start_cnt += 1
    if s[-1] == "A":
        A_end_cnt += 1
    AB_cnt += s.count('AB')
ans = min(A_end_cnt,B_start_cnt)+AB_cnt
if A_end_cnt == BA_cnt and B_start_cnt == BA_cnt:
    ans -= 1
if A_end_cnt == BA_cnt+1 and B_start_cnt == BA_cnt+1:
    ans += 1
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
def task_c():
    n = int(input())
    sss = [input().strip() for _ in range(n)]
    
    def count_ab(tt):
        c = 0
        for i in range(1, len(tt)):
            if tt[i-1:i+1] == 'AB':
                c += 1
        return c
    
    c_first_b = sum(1 for ss in sss if ss[:1] == 'B' and ss[-1:] != 'A')
    c_last_a = sum(1 for ss in sss if ss[:1] != 'B' and ss[-1:] == 'A')
    c_ab = sum(1 for ss in sss if ss[:1] == 'B' and ss[-1:] == 'A')
    c_include_ab = sum(count_ab(ss) for ss in sss)
    c = min(c_first_b+c_ab, c_last_a+c_ab) + c_include_ab
    if c_first_b == 0 and (c_first_b+c_ab == c_last_a+c_ab):
        c -= 1
    if c_last_a == 0 and (c_first_b+c_ab == c_last_a+c_ab):
        c -= 1
    print(c)
    
task_c()

Submission status: Wrong Answer

Solution code:
n = int(input())

a = 0
b = 0
c = 0
co = 0
for i in range(n):
	l = input()
	co += l.count("AB")
	if l[0] == "B":
		b += 1
	if l[-1] == "A":
		a += 1
	if l[-1] == "A" and l[0] == "B":
		c += 1

k = min(a,b,c)

if c == k:
	co += 2 * c
	co += min(a-2*k,b-2*k)
elif a == k:
	co += a
	kk = min(c-a,b-a)
	co += kk
	if kk == b-a:
		co += c - k - kk + 1
	else:
		co += a
else:
	co += b
	kk = min(c-b,a-b)
	co += kk
	if kk == a-b:
		co += c - k - kk + 1
	else:
		co += a


print(co)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=['' for i in range(n)]
for i in range(n):
  s[i]=input()
#print(n,s)
cnt=0
cnta=0
cntb=0
cntab=0
ans1=0
ans2=0
for i in range(n):
    cnt+=s[i].count('AB')
    if s[i][-1]=='A':
        cnta+=1
        if s[i][0]=='B':
            cntab+=1
    if s[i][0]=='B':
        cntb+=1
    

ans1=cnt+min(cnta,cntb)
ans2=cnt+min(cnta,cntb+cntab)
print(max(ans1,ans2))

Submission status: Wrong Answer

Solution code:
import sys
n = int(input())
s = [str(input()) for i in range(n)]
p = 0
q = 0
k = 0
l = 0

for i in range(n):
    if s[i][0] == 'B':
        if s[i][len(s[i]) - 1] == 'A':
            l = l + 1
        else:
            p = p + 1
    elif s[i][len(s[i]) - 1] == 'A':
        q = q + 1
    
    for r in range(len(s[i]) - 1):
        if s[i][r] =='A' and s[i][r + 1] == 'B':
            k = k + 1
#print([p,q,l,k])
dp = [[[0 for i in range(l+1)] for x in range(q+1)] for y in range(p+1)]

if q > 0 and l > 0:
    dp[0][1][1] = 1
if p > 0 and l > 0:
    dp[1][0][1] = 1
if p > 0 and q > 0 and l > 0:
    dp[1][1][0] = 1

if p > 0 and q > 0 and l > 0:
    for x in range(1,p + 1):
        for y in range(1, q + 1):
            for z in range(1, l + 1):
                dp[x][y][z] = max(dp[x - 1][y - 1][z], dp[x][y][z - 1]) + 1

elif p == 0 and q != 0:
    print(l)
    sys.exit()
elif p != 0 and q == 0:
    print(l)
    sys.exit()
elif p != 0 and q != 0:
    print(min(p, q))
    sys.exit()
elif p == 0 and q == 0:
    print(max(0, l - 1))
    sys.exit()

#print(dp)
print(dp[p][q][l] + 1)

Submission status: Wrong Answer

Solution code:
N=int(input())
s=list(input() for _ in range(N))
ans=0
count=0
a_count=0
b_count=0
for i in s:
    ans+=i.count('AB')
    if i[0]=='B'and i[-1]=='A':
        a_count+=1
        b_count+=1
    elif i[0]=='B':
        b_count+=1
    elif i[-1]=='A':
        a_count+=1
print(ans+min(a_count,b_count))

Submission status: Wrong Answer

Solution code:
import numpy as np
import re

n=int(input())
string_list=[input() for i in range(n)]
#print(string_list)

check_sheet = np.zeros((len(string_list),6))
for u,string in enumerate(string_list):
  # そもそもA,B単発の可能性
  if len(string) == 1:
    if string[0] == "A":
      check_sheet[u][4] = 1
    elif string[0] == "B":
      check_sheet[u][5] = 1
  else:
    # "AB"が含まれる数のcount
    check_sheet[u][0] = len(re.findall("AB",string))
    # 頭に"A"がいる and 頭に"B"がいる
    if string[-1] == "A" and string[0] == "B":
      check_sheet[u][3] = 1
    elif string[-1] == "A":
      check_sheet[u][1] = 1
    elif string[0] == "B":
      check_sheet[u][2] = 1

# AB,-A,B-,B-A,A,B
# どんどん組みを作ったやつは引いていった方があとで計算しやすい
sums=np.sum(check_sheet,axis=0)
#print(sums)
_c = min(sums[1],sums[2])
c = min(sums[4],sums[5])
counts = sums[0] + _c + c
sums[1:3] -= _c
sums[4:] -= c
#print(sums)
if sums[3] != 0:
  counts += (sums[3]-1)
  ## B-Aに、必ず1つはつけられる！が、残ってる組み合わせは知っておきたい...
  ## -A,Bの組み合わせ
  if sums[1] > 0 and sums[5] > 0:
    # B-Aの両端にまずつける
    counts += 2
    # その上で、残ってる数のウチ作れる分だけ作って追加
    counts += min(sums[1]-1,sums[5]-1)
  ## B-,Aの組み合わせでも同様
  elif sums[2] > 0 and sums[4] > 0:
    # B-Aの両端にまずつける
    counts += 2
    # その上で、残ってる数のウチ作れる分だけ作って追加
    counts += min(sums[2]-1,sums[4]-1)
  ## 全部0とか出なければ、+1
  elif np.sum(sums[1:3]) != 0 and np.sum(sums[4:]): 
    counts += 1
else:
  # 組み合わせが適切であれば追加できる
  if sums[1] > 0 and sums[5] > 0:
    counts += min(sums[1],sums[5])
  elif sums[2] > 0 and sums[4] > 0:
    counts += min(sums[2],sums[4])
print(int(counts))

Submission status: Wrong Answer

Solution code:
N = int(input())
counter = 0
end_a = 0
start_b = 0
start_b_end_a = 0
for n in range(N):
    s = input()
    for i in range(len(s) - 1):
        if s[i:i + 2] == 'AB':
            counter += 1
    if s[-1] == 'A':
        end_a += 1
    if s[0] == 'B':
        start_b += 1
    if s[-1] == 'A' and s[0] == 'B':
        start_b_end_a += 1
if start_b_end_a == 1 and end_a == 1 and start_b == 1:
    print(counter)
elif N == start_b_end_a:
    print(counter + min([end_a, start_b]) - 1)
else:
    print(counter + min([end_a, start_b]))

Submission status: Wrong Answer

Solution code:
import itertools
n=int(input())
s=[input() for i in range(n)]
S=list(itertools.permutations(s))
target='AB'
count=0
for i in range(n):
    S[i] = "".join(S[i])
    if target in S[i]:
        count+=1
print(count)

Submission status: Wrong Answer

Solution code:
# import random
#
# dist = ["#","."]
#
# f = open("in_sample.txt","w")
#
# f.write("1000 1000\n")
#
# for i in range(1000):
#     temp =[]
#     for j in range(1000):
#         temp.append(random.choice(dist))
#     f.writelines(temp)
#     f.write("\n")


n = int(input())
count = 0
enda = 0
startb = 0
both = 0
for i in range(n):
    s = input()
    flag = False
    for i in range(len(s)):
        if flag and s[i] == "B":
            count += 1
            flag = False
        else:
            flag = False
        if s[i] == "A":
            flag = True
    if s[0] == "B" and s[-1] == "A":
        both += 1
    if s[0] == "B":
        startb += 1
    if s[-1] == "A":
        enda += 1


startb = startb-both
enda = enda-both

# print(count)
# print(both)
# print(enda)
# print(startb)

mi = min(startb,enda)
ma = max(startb,enda)
left = ma-mi

ans = count + mi
if both > left:
    if left == 0:
        ans += both-1
    else:
        ans += both
elif both == left:
    ans += both
else:
    ans += both

ans2 = count

if both > mi:
    ans2 += mi*2
    if left == 0:
        ans2 += both - mi -1;
    else:
        ans2 += both - mi;

print(max(ans,ans2))

Submission status: Wrong Answer

Solution code:
import math
N = int(input())
l = []
for i in range(N):
   l.append(input())

default = sum(['AB' in i for i in l])

#only末尾Aの数
a = sum([i[-1]=='A' and i[0]!='B' for i in l])
#only先頭Bの数
b = sum([i[0]=='B' and i[-1]!='A' for i in l])
#先頭Bかつ末尾Aの数
ab = sum([i[0]=='B' and i[-1]=='A' for i in l])

print("default = ", str(default))
print("a = ", str(a))
print("b = ", str(b))
print("ab = ", str(ab))

if a == b:
    if ab > a:
        num = 2 * a + ab - a -1
    elif ab == a:
        num = 2 * a
    elif ab < a:
        num = 2 * ab + a - ab
else:
    min = min(a, b)
    max = max(a, b)
    gap = abs(a-b)
    if ab <= min:
        print("!!")
        num = ab * 2 + gap - ab
    elif ab > min:
        print("!!!")
        num = min * 2 + ab - min - 1

print(num + default)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
for _ in range(N):
    s.append(input())
import copy
S = copy.deepcopy(s)
both = []
A_tail = []
B_head = []
other = []
for text in S:
    if text[0] == "B" and text[-1] == "A":
        both.append(text)
    elif text[0] == "B":
        B_head.append(text)
    elif text[-1] == "A":
        A_tail.append(text)
    else:
        other.append(text)
concat = []
for both_text in both:
    concat.extend(both_text)
a_idx = []
for idx,A_tail_text in enumerate(A_tail):
    if len(B_head) >= 1:
        concat.extend(A_tail_text)
        concat.extend(B_head[0])
        B_head.pop(0)
    else:
        a_idx.append(idx)
a_rest = []
for idx in a_idx:
    a_rest.append(A_tail[idx])
cnt = 0
for i in range(len(concat)-1):
    if concat[i:i+2] == ["A","B"]:
        cnt += 1
for oth in other:
    for i in range(len(oth)-1):
        if oth[i:i+2] == "AB":
            cnt += 1
for oth in a_rest:
    for i in range(len(oth)-1):
        if oth[i:i+2] == "AB":
            cnt += 1
for oth in B_head:
    for i in range(len(oth)-1):
        if oth[i:i+2] == "AB":
            cnt += 1

Submission status: Wrong Answer

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:
    cnt -=1
print(cnt+min(start,end))

Submission status: Wrong Answer

Solution code:
#! usr/bin/env python
# -*- coding: utf-8 -*-

from collections import deque
import heapq
import math
import bisect


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

    a = b = ab = 0
    ans = 0
    mx = 0
    for s in S:
        n = len(s)
        for j in range(n-1):
            if s[j] == "A" and s[j+1] == "B":
                ans += 1
        if s[0] == "B" and s[-1] == "A":
            ab += 1
        elif s[0] == "B":
            b += 1
        elif s[-1] == "A":
            a += 1

    X = min(a, b, ab)
    ans += 2 * X
    a -= X
    b -= X
    ab -= X

    if ab == 0:
        ans += min(a, b)
    else:
        ans += ab - 1
        if a or b:
            ans += 1

    print(ans)


if __name__ == '__main__':
    main()