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: Runtime Error

Solution code:
def solve():
    N = int(input())
    words = ["a"]*N
    for i in range(N):
        words[i] = list(input())
    A_list = []
    B_list = []
    AB_list = [] 
    AB_count = 0
    for i in range(N):
        tag_A = tag_B = tag_AB = 0
        for j in range(len(words[i])):
            if words[i][j] == "A" and j == len(words[i])-1:
                tag_A = 1
                tag_AB = 0
            elif words[i][j] == "A":
                tag_AB = 1
            elif words[i][j] == "B" and tag_AB == 1:
                tag_AB = 0
                AB_count += 1
            elif words[i][j] == "B" and j == 0:
                tag_B = 1
                tag_AB = 0
            else:
                tag_AB = 0
        if tag_A == 1 and tag_B == 1:
            AB_list.append(i)
        elif tag_A == 1:
            A_list.append(i)
        elif tag_B == 1:
            B_list.append(i)
        #print(tag_A,tag_B,AB_count,A_list,B_list,AB_list)

    if len(AB_list) > 0 and len(A_list) > 0 and len(B_list) > 0:
        count = AB_count + len(AB_list) + min(len(A_list),len(B_list))
    elif len(AB_list) > 0 and len(A_list) == 0 and len(B_list) == 0:
        count = AB_count + len(AB_list) -1
    elif len(AB_list) > 0 and (len(A_list) == 0 or len(B_list) == 0):
        count = AB_count + len(AB_list)
    else:
        count = AB_count + min(len(A_list),len(B_list))

    print(count)


 solve()

Submission status: Runtime Error

Solution code:
N = int(input())
s = []
temp_sum = 0
A_or_B_count = [0,0]
AB_count = 0
for i in range(N):
	aaa = input()
	temp_sum += aaa.count("AB")
	if aaa[0] == "B" and aaa[-1] == "A":
		AB_count += 1
	elif aaa[-1] == "A":
		A_or_B_count[0] += 1
	elif aaa[0] == "B":
		A_or_B_count[1] += 1
A_or_B_count.sort()
if A_or_B_count[0] + AB_count > A_or_B_count[1]:
	if A_or_B_count[0] == 0:
		print(temp_sum + min(N-1,AB_count - 1)
	else:
		AB_count -= (A_or_B_count[1] - A_or_B_count[0])
		print(temp_sum + min(N-1,AB_count + A_or_B_count[1]))
else:
	print(temp_sum + min(N - 1,A_or_B_count[0] + AB_count))

Submission status: Runtime Error

Solution code:

N = int(input())
countA = 0
countB = 0
countC = 0
kcount = 0

for i in range(N):
    K = input()
    kcount += K.count("AB")
    K = list(K)
    if K[0] == "B" and K[-1] == "A":
        countC += 1 
    if K[-1] == "A":
        countA += 1
    if K[0] == "B"
        countB += 1
if countC>=1 and (countB-countC)==0 and (countA-countC)==0:
    print(kcount+countC-1)
elif countC >=1 and (countB-countC)==0 and (countA-countC)>=1:
    print(kcount+countC)
elif countC >=1 and (countB-countC)>=1 and (countA-countC)==0:
    print(kcount+countC)
elif countB > countA:
    print(kcount+countA)
else:
    print(kcount+countB)

Submission status: Runtime Error

Solution code:
# N < 10000
N = int(input())

# len(s) < 10

count = 0
a, b, ba = 0, 0, 0
for i in range(N):
    s = input().rstrip()
    i = 0
    while True:
        i = s.find("AB", i)
        if i < 0:
            break
        i += 2
        count+=1

    if s[-1] == 'A':
        if s[0] == 'B':
            ba += 1
        else:
            a += 1
    elif s[0] == 'B':
        b += 1

e = int(input())
#print("*A=",a, ", B*=",b, "B*A=",ba, ",AB=", count, ",expected=", e)

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

Submission status: Runtime Error

Solution code:
N = int(input())
right_A = 0
left_B = 0
B_to_A = 0
AB_count = 0

for _ in range(N):
    target = input()
    AB_count += target.count('AB')
    if target[0] == 'B' and target[-1] == 'A':
        B_to_A += 1
    elif target[0] == 'B':
        left_B += 1
    elif target[-1] == 'A':
        right_A += 1

def recursive(x, y, z):
    if z == 0:
        return min(x, y)
    elif x == y == 0:
        return z - 1
    else:
        return recursive(x, y, z-1) + 1

print(recursive(right_A, left_B, B_to_A) + AB_count)

Submission status: Runtime Error

Solution code:
import re
N=int(input())
listA=[input() for i in range(N)]

firstB=0
endA=0
feAB=0
AB=0
for A in listA:
    AB+=len(re.findall("AB",i))
    print(len(re.findall("AB",i)))
    if i[0]=="B":
        firstB+=1
    if i[-1]=="A":
        endA+=1
        if i[0]=="B":
            feAB+=1
AB+=min([endA,firstB])
print(AB)

Submission status: Runtime Error

Solution code:
n=0
tmp = ''
a=0
b=0
n = input()
l = 0
sum = 0
arr = []
for i in n:
    tmp = input()
    arr.append(tmp)

for i in n:
    tmp = arr[i]
    l = len(tmp)
    if tmp[0] == 'B':
        b = b+1
    if tmp[l-1] == 'A':
        a = a+1
    
    tmpchar = ''
    for char in tmp:
        if char == 'B' and tmpchar == 'A':
            sum = sum +1
        tmpchar = char

if a==n and b ==n:
    a =a-1
if a>b:
    print(sum+b)
else: 
    print(sum + a)

Submission status: Runtime Error

Solution code:

v = [int(d) for d in input().split()]
f = []

for e in range(v[0]):
    f.append(input())
re = 0
for d in f:
    re += d.count('AB')
dd = [list(s) for s in f]


b = 0
a = 0

for q in dd:
    if q[0] == 'B':
        b += 1
    if q[-1] == 'A':
        a += 1

if a > b:
    ss = b
elif a < b:
    ss = a
elif a == b:
    ss == a

if ss == len(f):
    re -= 1
re = re + ss
print(re)

Submission status: Runtime Error

Solution code:
import re
N=int(input())
listA=[input() for i in range(N)]

firstB=0
endA=0
feAB=0
AB=0
for A in listA:
    AB+=len(re.findall("AB",i))
    print(len(re.findall("AB",i)))
    if i[0]=="B":
        firstB+=1
    if i[-1]=="A":
        endA+=1
        if i[0]=="B":
            feAB+=1
AB+=min([endA,firstB])
print(AB)

Submission status: Runtime Error

Solution code:
N = int(input())

ans = 0
dic = {"A": 0, "B": 0}
dic2 = {"AB": 0, "A": 0, "B": 0}
for i in range(N):
    S = list(str(input()))
    pre = S[0]
    for j in range(1, len(S)):
        if (S[j - 1] + S[j]) == "AB":
            ans += 1
    if S[-1] == "A":
        dic["A"] += 1
    if S[0] == "B":
        dic["B"] += 1

    if S[-1] == "A" and S[0] == "B":
        dic2["AB"] += 1
    elif S[-1] == "A":
        dic2["A"] += 1
    elif S[0] == "B":
        dic2["B"] += 1
if dic2["A"] == 0 and dic2["B"] == 0:
    print(ans + dic["AB"]//2)
else:
    print(ans + min(dic["A"], dic["B"]))

Submission status: Runtime Error

Solution code:
import re

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

num_end_with_A = 0
num_start_with_B = 0
num_both = 0
num_inner_AB = 0

for ss in s:
    res = re.findall('AB', ss)
    if res:
        num_inner_AB += len(res)
    if ss[0] == 'B' and ss[-1] == 'A':
        num_both += 1
    elif ss[0] == 'B':
        num_start_with_B += 1
    elif ss[-1] == 'A':
        num_end_with_A += 1


if num_end_with_A == num_start_with_B:
    print(num_inner_AB + num_end_with_a + max(num_both - 1, 0))
else:
    print(num_inner_AB + min(num_end_with_A, num_start_with_B) + num_both)

Submission status: Runtime Error

Solution code:
import itertools
N = int(input())
A=[]
for i in range(N):
    A.append(input())
X=0

B="".join(i)

Y=B.count("AB")
Z1=0
Z2=0
for i in A:
    C=pop[0]
    if(C=="A"):
        Z1+=1

for i in A:
    C=pop[-1]
    if(C=="B"):
        Z2+=1
Z3=0
if(Z1>Z2):
    Z3=Z2
elif(Z2>Z1):
    Z3=Z1
else:
    Z3=Z1
Y+=Z3


print(Y)

Submission status: Runtime Error

Solution code:
N = int(input())
a, b, bxxa, ab = 0, 0, 0, 0

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

if a>b :
    print(ab+b)
elif a==b and bxxa==a:
    print(ab+a-1)
else: 
    print(ab+a)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
sl = [input() for _ in range(n)]

xa = []
bx = []
ba = []
x = []
for s in sl:
    if s[0]=="B" and s[-1]=="A":
        ba.append(s)
    elif s[-1]=="A":
        xa.append(s)
    elif s[0]=="B":
        bx.append(s)
    else:
        x.append(s)
xa = xa[:-1]+[xa[-1]+"".join(ba)]

if len(xa)>=len(bx):
    for i in range(len(bx)):
        x.append(xa[i]+bx[i])
    x = x+xa[len(bx):]
else:
    for i in range(len(xa)):
        x.append(xa[i]+bx[i])
    x = x+bx[len(xa):]

res = "".join(x)
print(res.count("AB"))

Submission status: Runtime Error

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

from itertools import permutations as perm

p = perm(S,N)
count_list = []
for s in p:
    print(s)
    join = "".join(s)
    count_list.append(join.count("AB"))
print(max(count_list))

Submission status: Runtime Error

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

IB= [0] * (N)
LA = [0] * (N)
flag = True
Eflag = False
cntb= 0
cnta = 0
ans = 0
for i in range(N):
    if S[i][0] == 'B':
        IB[i] = 1
        cntb += 1
    if S[i][len(S[i])-1] == 'A' :
        LA[i] = 1
        cnta += 1
    if (IB[i] == 1 and LA[i] == 0) or (IB[i]==0 and LA[i] == 1):
        flag = False
    elif (IB[i] == 1 and LA[i] == 1):
        Eflag = True
    for j in range(len(S[i])):
        if S[i][j] == 'A' and S[i][j+1]=='B' : ans += 1
        
        
ans += min(cntb,cnta)
if Eflag and flag:    
    ans -= 1



print(ans)

Submission status: Runtime Error

Solution code:
i = 1
string = input("")
array = [string]
while i < num :
  strtemp = input("")
  array.append(strtemp)
  i+=1
front = 0
back = 0
is_a = 0
is_b = 0
is_ab = 0
for tmp in array :
  char = list(tmp)
  for tmp2 in char :
    if tmp2 == "A" :
      is_a = 1
      is_b = 0
    if is_a == 1 and tmp2 == "B" :
      is_ab += 1
      is_a = 0
    else :
      is_a = 0
      is_b = 1
      if char[0] == tmp2 :
        front += 1
  if is_a == 1 :
    back += 1
  is_a = 0
  is_b = 0
if front >= back :
  is_ab += back
elif back > front :
  is_ab += front
print(is_ab)

Submission status: Runtime Error

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

start = 0
end = 0
flg = False
c = 0
for x in s:
    if 'AB' in x:
        c += 1
    if x.startswith('B'):
        start += 1
        if x.endswith('A'):
            flg = True
    if x.endswith('A'):
        end += 1
if start = end:
    c += start
    if flg:
        c  -= 1
else if start > end:
    c += end
else:
    c += start
print(c)

Submission status: Runtime Error

Solution code:
i = 1
string = input("")
array = [string]
while i < num :
  strtemp = input("")
  array.append(strtemp)
  i+=1
front = 0
back = 0
is_a = 0
is_b = 0
is_ab = 0
for tmp in array :
  char = list(tmp)
  for tmp2 in char :
    if tmp2 == "A" :
      is_a = 1
      is_b = 0
    if is_a == 1 && tmp2 == "B" :
      is_ab += 1
      is_a = 0
    else :
      is_a = 0
      is_b = 1
      if char[0] == tmp2 :
        front += 1
  if is_a == 1 :
    back += 1
  is_a = 0
  is_b = 0
if front >= back :
  is_ab += back
elif back > front :
  is_ab += front
print is_ab

Submission status: Runtime Error

Solution code:
N = int(input())
a_count =0
b_count =0
ab_count =0
ab_alt =0
for i in range(N):
    test = str(input())
    if test[0] == "B":
        b_count +=1
        flag =1
    if test[-1] == "A":
        a_count += 1
        if flag == 1:
            flag =0
            ab_alt +=1
    ab_count += test.count("AB")
if ab_alt == b_count:
    if ab_alt == a_count:
        a_count += -1
print(ab_count+min(a_count,b_count))

Submission status: Runtime Error

Solution code:
ans=0
f_a=0
b_b=0
a_b=0
str_list=[]
N= int(input())
for i in range(N):
    str=input()
    ans=ans+str.count("AB")
    if(str[-1]=="A"):
        f_a=f_a+1
    if(str[0]=="B"):
        b_b=b_b+1
    if(str[-1]=="A"and str[0]=="B"):
        a_b=a_b+1


if(f_a==N and b_b==N):
    ans=ans+n-1
elif((f_a==a_b)and(b_b==a_b)):
    ans=ans+n-1
elif(f_a< b_b):
    ans=ans+f_a
else:
    ans=ans+b_b

#print(f_a)
#print(b_b)
print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
s_list = [input() for _ in range(N)]
ans = 0
ans_list = [0, 0, 0]
for s in s_list:
  ans += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    ans_list[0] += 1
  elif s[0] == 'B':
    ans_list[1] += 1
  elif s[-1] == 'A':
    ans_list[2] += 1

if ans_list[1] == 0:
  if ans_list[0] != 0:
    if ans_list[2] != 0:
      ans += ans_list[0]
    else:
      ans += ans_list[0]-1
else:
  if ans_list[0] != 0:
    if ans_list[2] != 0:
      ans += ans_list[0] + min(ans_list[1], ans_list[2])
    else:
      ans += ams_list[0]
  else:
    ans += min(ans_list[1], ans_list[2])
print(ans)

Submission status: Runtime Error

Solution code:
n = input("")
num = int(n)
i = 1
string = input("")
array = [string]
while i < num :
  strtemp = input("")
  array.append(strtemp)
  i+=1
front = 0
back = 0
is_a = 0
is_b = 0
is_ab = 0
for tmp in array :
  char = list(tmp)
  for tmp2 in char :
    if tmp2 == "A" :
      is_a = 1
      is_b = 0
    if is_a == 1 && tmp2 == "B" :
      is_ab += 1
      is_a = 0
    else :
      is_a = 0
      is_b = 1
      if char[0] == tmp2 :
        front += 1
  if is_a == 1 :
    back += 1
  is_a = 0
  is_b = 0
if front >= back :
  is_ab += back
elif back > front :
  is_ab += front
print(is_ab)

Submission status: Runtime Error

Solution code:
N=int(input())
XA=0
BA=0
BX=0
internalAB=0
for t in range(N):
    i=input()
    headUsed=False
    footUsed=False
    for x,j in enumerate(i):
        if x==len(i)-1:break
        if j=="A" and i[x+1]=="B":
            internalAB+=1
            if x==0:headUsed=True
            if x==len(i)-2:footUsed=True
    if i[0]=="B" and not headUsed:
        if i[-1]=="A" and not footUsed:
            BA+=1
        else:BX+=1
    elif i[-1]=="A" and not footUsed:
        XA+=1
ans=internalAB+BA+min(XA,BX)
if XA=BX=0:ans-=1
print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
sl = [input() for _ in range(n)]

xa = []
bx = []
ab = []
x = []
for s in sl:
    if s[0]=="B" and s[-1]=="A":
        ab.append(s)
    elif s[-1]=="A":
        xa.append(s)
    elif s[0]=="B":
        bx.append(s)
    else:
        x.append(s)
ab = ["".join(ab)]

if len(ab)>len(bx):
    bx.append(ab[0])
else:
    xa.append(ab[0])

if len(xa)>=len(bx):
    for i in range(len(bx)):
        x.append(xa[i]+bx[i])
    x = x+xa[len(bx):]
else:
    for i in range(len(xa)):
        x.append(xa[i]+bx[i])
    x = x+xb[len(xa):]
res = "".join(x)
print(res.count("AB"))

Submission status: Runtime Error

Solution code:
N=int(input())
s=[]
total=0
A=0
B=0
for i in range(N):
    tmp=input()
    while True:
        if len(tmp)>=2:
            if "AB" in tmp[:2]:
                total+=1
                tmp=tmp[2:]
            else:
                break
        else:
            break
    while True:
        
        if len(tmp)>=2:
            if "AB" in tmp[-2:]:
                total+=1
                tmp=tmp[-2:]
            else:
                break
        else:
            break
    total+=tmp.count("AB")
    if len(tmp)>0:
        if tmp[0]=="B":
            B+=1
        if tmp[-1]=="A":
            A+=1"A":
            A+=1

print(total+min(A,B))

Submission status: Runtime Error

Solution code:
n=int(input())
a=0
b=0
ab=0
ba=0
for i in range(n):
  s=input()
  ab+=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':
    ba+=1
if ba*2==a+b+1 or ba*2==a+b:
  print(ans+ba-1)
else:
  print(ab+min(a,b))

Submission status: Runtime Error

Solution code:
ans = 0
first_b = 0
last_a = 0
same = 0

N = int(input())

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

ans += min(first_b, last_a)
if same > 0 and first_b ==  last_a and first_b = same:
    ans -=1
 print(ans)

Submission status: Runtime Error

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

result = 0
ABAB = 0
A = 0
B = 0

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

for S in s:
    AB = S.count("AB")
    result += AB
    if S[0] == "B" and S[-1] == "A":
        ABAB += 1
    elif S[0] == "B":
        B += 1
    elif S[-1] == "A":
        A += 1




if ABAB >= 1:
    onon = onon + ABAB - 1

if A >= 1:
    onon += 1
if B >= 1:
    onon += 1



print(result + onon)

Submission status: Runtime Error

Solution code:
def countAB(S):
  ct=0
  flg = True
  pos=0
  while flg:
    idx = S.find('AB',pos)
    if idx!=-1:
      ct+=1
    else:
      flg = False
    pos = idx + 2
  return ct

N = int(input())

num_AB = 0
num_A = 0
for n in range(N):
  S = input()
  num_AB += countAB(S)
  if S[len(S)-1]=='A':
    num_A += 1
  if S[0]=='B':
    num_B += 1

num_AB_cmb = min(num_A,num_B)
if num_A == N and num_B == N:
  num_AB_cmb = N-1

print("{0}".format(num_AB + num_AB_cmb))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
#include <sys/time.h>
using namespace std;

#define rep(i,n) for(long long i = 0; i < (long long)(n); i++)
#define repi(i,a,b) for(long long i = (long long)(a); i < (long long)(b); i++)
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
#define mt make_tuple
#define mp make_pair
template<class T1, class T2> bool chmin(T1 &a, T2 b) { return b < a && (a = b, true); }
template<class T1, class T2> bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }

using ll = long long; using vll = vector<ll>; using vvll = vector<vll>; using P = pair<ll, ll>;
ll ugauss(ll a, ll b) { if (!a) return 0; if (a>0^b>0) return a/b; else return (a+(a>0?-1:1))/b+1; }
ll lgauss(ll a, ll b) { if (!a) return 0; if (a>0^b>0) return (a+(a>0?-1:1))/b-1; else return a/b; }
template <typename T, typename U> ostream &operator<<(ostream &o, const pair<T, U> &v) {  o << "(" << v.first << ", " << v.second << ")"; return o; }
template<size_t...> struct seq{}; template<size_t N, size_t... Is> struct gen_seq : gen_seq<N-1, N-1, Is...>{}; template<size_t... Is> struct gen_seq<0, Is...> : seq<Is...>{};
template<class Ch, class Tr, class Tuple, size_t... Is>
void print_tuple(basic_ostream<Ch,Tr>& os, Tuple const& t, seq<Is...>){ using s = int[]; (void)s{0, (void(os << (Is == 0? "" : ", ") << get<Is>(t)), 0)...}; }
template<class Ch, class Tr, class... Args> 
auto operator<<(basic_ostream<Ch, Tr>& os, tuple<Args...> const& t) -> basic_ostream<Ch, Tr>& { os << "("; print_tuple(os, t, gen_seq<sizeof...(Args)>()); return os << ")"; }
ostream &operator<<(ostream &o, const vvll &v) { rep(i, v.size()) { rep(j, v[i].size()) o << v[i][j] << " "; o << endl; } return o; }
template <typename T> ostream &operator<<(ostream &o, const vector<T> &v) { o << '['; rep(i, v.size()) o << v[i] << (i != v.size()-1 ? ", " : ""); o << "]";  return o; }
template <typename T> ostream &operator<<(ostream &o, const deque<T> &v) { o << '['; rep(i, v.size()) o << v[i] << (i != v.size()-1 ? ", " : ""); o << "]";  return o; }
template <typename T>  ostream &operator<<(ostream &o, const set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]";  return o; }
template <typename T>  ostream &operator<<(ostream &o, const unordered_set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]";  return o; }
template <typename T, typename U>  ostream &operator<<(ostream &o, const map<T, U> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]";  return o; }
template <typename T, typename U, typename V>  ostream &operator<<(ostream &o, const unordered_map<T, U, V> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it; o << "]";  return o; }
vector<int> range(const int x, const int y) { vector<int> v(y - x + 1); iota(v.begin(), v.end(), x); return v; }
template <typename T> istream& operator>>(istream& i, vector<T>& o) { rep(j, o.size()) i >> o[j]; return i;}
template <typename T, typename S, typename U> ostream &operator<<(ostream &o, const priority_queue<T, S, U> &v) { auto tmp = v; while (tmp.size()) { auto x = tmp.top(); tmp.pop(); o << x << " ";} return o; }
template <typename T> ostream &operator<<(ostream &o, const queue<T> &v) { auto tmp = v; while (tmp.size()) { auto x = tmp.front(); tmp.pop(); o << x << " ";} return o; }
template <typename T> ostream &operator<<(ostream &o, const stack<T> &v) { auto tmp = v; while (tmp.size()) { auto x = tmp.top(); tmp.pop(); o << x << " ";} return o; }
template <typename T> unordered_map<T, ll> counter(vector<T> vec){unordered_map<T, ll> ret; for (auto&& x : vec) ret[x]++; return ret;};
void vizGraph(vvll& g, int mode = 0, string filename = "out.png") { ofstream ofs("./out.dot"); ofs << "digraph graph_name {" << endl; set<P> memo; rep(i, g.size())  rep(j, g[i].size()) { if (mode && (memo.count(P(i, g[i][j])) || memo.count(P(g[i][j], i)))) continue; memo.insert(P(i, g[i][j])); ofs << "    " << i << " -> " << g[i][j] << (mode ? " [arrowhead = none]" : "")<< endl;  } ofs << "}" << endl; ofs.close(); system(((string)"dot -T png out.dot >" + filename).c_str()); }
struct timeval start; double sec() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec - start.tv_sec) + (tv.tv_usec - start.tv_usec) * 1e-6; }
size_t random_seed; struct init_{init_(){ ios::sync_with_stdio(false); cin.tie(0); gettimeofday(&start, NULL); struct timeval myTime; struct tm *time_st; gettimeofday(&myTime, NULL); time_st = localtime(&myTime.tv_sec); srand(myTime.tv_usec); random_seed = RAND_MAX / 2 + rand() / 2; }} init__;
#define ldout fixed << setprecision(40) 

#define EPS (double)1e-14
#define INF (ll)1e18
#define mo  (ll)(1e9+7)

int main(void) {
    ll n; cin >> n;
    vector<string> s(n); cin >> s;
    vector<string> r(n); 
    ll ret = 0;
    rep(_, n) {
        string t = s[_];
        while (t.size() > 1) {
            bool found = 0;
            string tmp;
            rep(i, t.size()-1) {
                if (t[i] == 'A' && t[i+1] == 'B') {
                    found = 1;
                    ret++;
                    rep(j, t.size()) if (j != i && j != i+1) {
                        tmp += t[j];
                    }
                    t = tmp;
                    break;
                }
                if (found) break;
            }
            if (!found) break;
        }
        r[_] = t;
    }
//    cout << r << endl;
    ll a = 0;
    ll b = 0;
    ll bxa = 0;
    ll xa = 0;
    ll bx = 0;
    rep(i, n) {
        if (r[i].size() == 1) {
            if (r[i][0] == 'A') a++;
            else if (r[i][0] == 'B') b++;
        } else {
            if (r[i][0] == 'B' && r[i][r[i].size()-1] == 'A') bxa++;
            else if (r[i][r[i].size()-1] == 'A') xa++;
            else if (r[i][0] == 'B') bx++;
        }
    }
//    cout << ret << endl;
//    cout << a << b << bxa << " " << xa << " " << bx << endl;

    if (bxa > 0) {
        ret += bxa - 1;
        bxa = 1;
    }

    if (bxa == 1) {
        if (a > 0) {
            ret++;
            a--;
        } else if (xa > 0) {
            ret++;
            xa--;
        }
        if (b > 0) {
            ret++;
            b--;
        } else if (bx > 0) {
            ret++;
            bx--;
        }
        bxa = 0;
    }

    ret += min(a+xa, bx+b);
    cout << ret << endl;

    return 0;
}

Submission status: Runtime Error

Solution code:
ans=0
f_a=0
b_b=0
str_list=[]
N= int(input())
for i in range(N):
    str=input()
    ans=ans+str.count("AB")
    if(str[-1]=="A"):
        f_a=f_a+1
    if(str[0]=="B"):
        b_b=b_b+1

if(f_a==N and b_b==N):
    ans=ans+n-1
elif(f_a<= b_b):
    ans=ans+f_a
else:
    ans=ans+b_b

print(ans)

Submission status: Runtime Error

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

count_AB = [s[i].count("AB") for i in range(N)]

headB = 0
tailA = 0
headB_and_tailA = 0
for i in range(N):
    #print("i =", i)
    if s[i][0] == 'B':
        if s[i][-1] != 'A':
            #print("headB")
            headB += 1
        else:
            headB_and_tailA += 1
            #print("both")
    elif s[i][-1] == 'A':
        tailA += 1
        #print("tailA")

"""
print("both =", headB_and_tailA)
print("headB = ", headB)
print("tailA = ", tailA)
"""
result = sum(count_AB) + min(headB, tailA)
headB -= min(headB, tailA)
tailA -= min(headB, tailA)
for _ in range(headB_and_tailA):
    if tailA > 0:
        result += 1
    elif tailB > 0:
        result += 1
    else:
        tailA += 1
#print("sum = ", sum(count_AB))
    
print(result)

Submission status: Runtime Error

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

count = 0
ba = 0
wa = 0
bw = 0
for s in S:
    count += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        ba += 1
    elif s[0] == 'B':
        bw += 1
    elif s[-1] == 'A':
        wa += 1

if ba:
    count += ba - 1
    ba = 1
if ba:
    if wa and bw:
        count += 2
        wa -= 1
        bw -= 1
        ba -= 1
    if ba:
        if wa < bw:
            wa += 1
        else:
            bw += 1
count += min(wa,bw)

print(count)´

Submission status: Runtime Error

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

result = 0
ABAB = 0
A = 0
B = 0

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

for S in s:
    AB = S.count("AB")
    result += AB
    if S[0] == "B" and S[-1] == "A":
        ABAB += 1
    elif S[0] == "B":
        B += 1
    else S[-1] == "A":
        A += 1


if A >= B:
    onon = B
    amari = A - B
else:
    onon = A
    amari = B - A

if ABAB >= 1:
    onon = onon + ABAB - 1

if amari >= 1:
    onon = onon + 1

print(result + onon)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
R,G,B,N=(int(x) for x in input().split())
count=0
for r in range(0,N+1):
    if (r*R>N):
        break
    for g in range(0,N-r*R+1):
        if(r*R-g*G>N):
            break
        if((N-r*R-g*G)%B==0 and (N-r*R-g*G)/B>=0):
            count+=1
print(count)

Submission status: Runtime Error

Solution code:
N = int(input())
s = 0
t = 0
u = 0
A = []
for i in range(N):
  m = input()
  A.append(m)
  u += m.count("AB")
  if m[0] == B:
    s += 1
  if m[-1] == A:
    t += 1
u += min(s, t)
print(u)

Submission status: Runtime Error

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