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:
#!/usr/bin/env python3
import sys
import itertools
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" and if s[i][-1] == "A":
            AendBstart += 1
        elif s[i][0] == "B":
            Bstart += 1
        elif s[i][-1] == "A":
            Aend += 1

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

    # 愚直
    # print("愚直")
    # ans = []
    # for kumi in itertools.permutations(s, N):
    #     ans.append("".join(kumi).count("AB"))
    # print(max(ans))
    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: Runtime Error

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

cnt_ab = 0
cnt_a = 0
cnt_b = 0
cnt_ba = 0

for i in range(N):
    cnt_ab += List[i].count("AB")
for j in range(N):
    if (List[j][-1]=="A")&(List[j][0]!="B"):
        cnt_a+=1
for k in range(N):
    if (List[k][0]=="B")&(List[k][-1]!="A"):
        cnt_b +=1
for l in range(N):
    if (List[l][-1]=="A")&(List[l][0]=="B"):
        cnt_ba+=1

if (cnt_ba<=abs(cnt_a-cnt_b)):
    cnt = cnt_ab + min(cnt_a, ant_b) + cnt_ba
    print(cnt)
else:
    cnt = cnt_ab + min(cnt_a, cnt_b) + cnt_ba-1
    print(cnt)

Submission status: Runtime Error

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

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

print(_c)

# 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,_c))

Submission status: Runtime Error

Solution code:
N = int(input())
s_list = []
count = 0
n, m, l = 0, 0, 0
 
for i in range(N):
  s = input()
  s_list.append(s)
  count += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    n += 1
    continue
  elif s[-1] == 'A':
    m += 1
  elif s[0] == 'B':
    l += 1

if m == 0 and l == 0:
  if n == 0:
    print(int(count))
  else:
  print(int(count + (n - 1)))
else:
  print(int(count + min(n+m, n+l)))

Submission status: Runtime Error

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

_c=c
_c+=max(0,c3-1)
_c1=c1
_c2=c2
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(c)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

Solution code:
import sys

def main():
    input = sys.stdin.readline
    N = int(input())
    ans = 0
    ba = 0  # Num. of str that the first letter is B and the last one is A.
    xb = 0  # Num. of str that the last letter is B and the first one is not A.
    ax = 0  # Num. of str that the first letter is A and the last one is not B.
    for _ in range(N):
        s = str(input().strip())

        # Count the number of AB contained in the initial strings.
        for i in range(len(s)):
            if s[i:i+2] == 'AB':
                ans += 1

        if s[0] == 'B' and s[-1] == 'A':
            ba += 1
        elif s[0] == 'B':
            xb += 1
        elif s[-1] == 'A':
            ax += 1

    if max(xb, ax) == 0:
        # N of ba make N-1 new "AB".
        # BxxA + BxxA + ... + BxxA -> BxxABxxAB...ABxxA
        ans += ba - 1

    else:  # There is at least one bx or ax.
        # N of ba make N-1 new "AB" and a ba.
        #   ba + ba + ... + ba -> baba...ba = ba
        # The last remaining ba and bx/ax make a new "AB" and a new bx/ax.
        #   ba + bx -> bABx = bx,  xa + ba -> xABa = xa
        # Then, bx and xa make a new "AB".
        #   xa + bx -> xABx 
        ans += ba + min(xa, bx)

    return ans


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

Submission status: Runtime Error

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

ans = 0
b_pre = []
a_suf = []
ab = []
for st in s:
    if st.startswith("B") and st.endswith("A"):
        ans += st.count("AB")
        ab.append(st)
    elif st.startswith("B"):
        ans += st.count("AB")
        b_pre.append(st)
    elif st.endswith("A"):
        ans += st.count("AB")
        a_suf.append(st)
    else:
        ans += st.count("AB")

if len(b_pre) - len(a_suf) > 1:
    while len(b_pre) - len(a_suf) > 1:
        for b in b_pre:
            if b.endswith("A"):
                a_suf.append(b)
                b_pre.remove(b)
            if len(b_pre) - len(a_suf) <= 1:
                break
elif len(a_suf) - len(b_pre) > 1:
    while len(a_suf) - len(b_pre) > 1:
        for a in a_suf:
            if b.startswith("B"):
                b_pre.append(b)
                a_suf.remove(b)
            if len(a_suf) - len(b_pre) > 1:
                break

ans += math.ceil(len(ab)/2)
if len(b_pre) < len(a_suf):
    ans += len(b_pre)
    ans += len(a_suf) - len(b_pre)
else:
    ans += len(a_suf)
    ans += len(b_pre) - len(a_suf)


print(ans)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void input_vector(vector<string>& v) {
    string tmp;
    cin >> tmp;
    v.push_back(tmp);
}

int find_all(const std::string str, const std::string subStr) {
    int count = 0;
    int subStrSize = subStr.size();
    int pos = str.find(subStr);

    while (pos != std::string::npos) {
        count++;
        pos = str.find(subStr, pos + subStrSize);
    }

    return count;
}

int main() {
    int n;
    cin >> n;

    vector<string> v;
    for (int i = 0; i < n; ++i) {
        input_vector(v);
    }

    string target = "AB";
    vector<int> nums_ab;
    nums_ab.reserve(n);

    for (int j = 0; j < n; ++j) {
        nums_ab.push_back(find_all(v.at(j), target));
    }

    int cnt_end_a = 0;
    int cnt_top_b = 0;
    int both = 0;
    bool is_b = false;

    for (int j = 0; j < n; ++j) {
        if (v.at(j).at(0) == 'B') {
            cnt_top_b++;
            is_b = true;
        }
        if (v.at(j).at(v.at(j).size()-1) == 'A') {
            cnt_end_a++;
            if (is_b) {
                cnt_top_b--;
                cnt_end_a--;
                both++;
            }
        }

        is_b = false;
    }

    int ans = 0;

    for (int k = 0; k < n; ++k) {
        ans += nums_ab.at(k);
    }

    if (both == 0) {
        ans += min(cnt_end_a, cnt_top_b);
    } else {
        if (cnt_end_a == 0 && cnt_top_b == 0) {
            ans += both-1;
        } else {
            ans += both+min(cnt_end_a, cnt_top_b);
        }
    }

    cout << ans << endl;
}

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
coo= 0

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

    elif q[0] == 'B' & q[-1] != 'A':
        b += 1
    elif q[-1] == 'A' & q[0] != 'B':
        a += 1

if coo != 0 & a == 0 & b == 0:
    ss = coo - 1
else:
    ss = min(coo+a,coo+b)


print(re + ss)

Submission status: Runtime Error

Solution code:
n=int(input())
s=list(input() for _ in range(n))
m,i,f,both=0,0,0,0

for i in range(n):
    m +=s[i].count("AB")
    if s[i][0]=="B":
        i +=1
    i==i+1-1
    if s[i][-1]=="A":
        f +=1
    i==i+1-1
    if s[i][0]=="B" and s[i][1]=="A":
        both+=1
        i-=1
        f-=1

if both!=0:
    if i!=0 and f!=0:
        print(m+both+min(i,f)-1)
    else:
        print(m+both+min(i,f))

else:
    print(min(i,f))

Submission status: Runtime Error

Solution code:
n=int(input())
s=list(input() for _ in range(n))
m,i,f,both=0,0,0,0

for i in range(n):
    m +=s[i].count("AB")
    if s[i][0]=="B":
        i +=1
    if s[i][1]=="A":
        f +=1
    if s[i][0]=="B" and s[i][1]=="A":
        both+=1
        i-=1
        f-=1

if both!=0:
    if i!=0 and f!=0:
        print(m+both+min(i,f)-1)
    else:
        print(m+both+min(i,f))

else:
    print(min(i,f))

Submission status: Runtime Error

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

ans = 0
head_b = 0
tail_a = 0
headAndTail = 0

for s in s_list:
    if 'AB' in s:
        ans += 1
    if s.startswith('B') and s.endswith('A')::
       headAndTail += 1
    elif s.startswith('B'):
        head_b += 1
    elif s.endswith('A'):
        tail_a += 1

ans += min([head_b, tail_a])

if head_b == 0 and tail_a == 0:
    ans += max([0,headAndTail-1])
else:
    ans += headAndTail

print(ans)

Submission status: Runtime Error

Solution code:
n=int(input())
s=list(input() for _ in range(n))
m,i,f,both=0,0,0,0

for i in range(n):
    m +=s[i].count("AB")
    if s[i][0]=="B":
        i +=1
    if s[i][-1]=="A":
        f +=1


if both!=0:
    if i!=0 and f!=0:
        print(m+both+min(i,f)-1)
    else:
        print(m+both+min(i,f))

else:
    print(min(i,f))

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, s: "List[str]"):
    x = 0
    a = 0
    b = 0
    for i in s:
        if(i[0] == 'B' and i[-1] == 'A'):
            x += 1
        elif(i[-1] == 'A'):
            a += 1
        elif(i[0] == 'B'):
            b += 1

    # ans1 = max(0,x-1) + (min(a,b) if a==b else min(a,b)+1)    
    
    if(x == 0):
        if(a == b):
            ans1 = min(a,b)
    else:
        ans1 = max(0,x-1)+min(a,b)
        if(a != b):
            ans1 += 1

    
    # ans1 = max(0,x-1) 
    # if(a == b):
    #     ans1 += min(a,b)
    # else:
    #     if(x == 0):
    #         ans1 += min(a,b)
    #     else:
    #         ans1 += min(a,b)+1 
    

    ans2 = 0
    for i in s:
        ans2 += i.count('AB')

    print(ans1+ans2)
    
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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: Runtime Error

Solution code:
N = int(input())
s =[]
count=0
Acount=0
Bcount=0
BAcount=0
for i in range(N):
    S = input()
    #s.append(S)
    ##AB inside
    for j in range(len(S)-1):
        if S[j] == 'A' and S[j+1]=='B':
            count+=1
    if S[0]=='B' and S[-1]=='A':
        BAcount+=1
    elif S[0]=='B':
        Bcount+=1
    elif S[-1]=='A':
        Acount+=1
#BAを先にくっつける
if BAcount >0:
    count+=BAcount-1
    BAcount=1
    ba = [BAcount,Bcount,Acount]
else:
    BAcount=0
    ba = [BAcount,Bcount,Acount]
#0が含まれているとき
ba = [i for i in ba if not i == 0]
minba =min(ba)
if BAcount == minba and len(ba)==3:
    count+=minba*2
    for i in range(3):
        ba[i] = ba[i]-minba
    ba = [i for i in ba if not i == 0]
    if len(ba) == 2:
        count+= min(ba)
else:
    if len(ba) == 2:
        count+= min(ba)
print(count)

Submission status: Runtime Error

Solution code:
n=int(input())
s=list(input() for _ in range(n))
m,i,f,both=0,0,0,0

for i in range(n):
    m +=s[i].count("AB")
    if s[i][0]=="B":
        i +=1
    if s[i][-1]=="A":
        f +=1
    if s[i][0]=="B" and s[i][1]=="A":
        both+=1
        i-=1
        f-=1

if both!=0:
    if i!=0 and f!=0:
        print(m+both+min(i,f)-1)
    else:
        print(m+both+min(i,f))

else:
    print(min(i,f))

Submission status: Runtime Error

Solution code:
n=int(input())
s=list(input() for _ in range(n))
m,i,f,both=0,0,0


if both!=0:
    if i==0 and f==0:
        print(m+both+min(i,f)-1)
    else:
        print(m+both+min(i,f))

else:
    print(min(i,f))

Submission status: Runtime Error

Solution code:
n=int(input())
s=list(input() for _ in range(n))
m,i,f,both=0,0,0

for i in range(n):
    m +=s[i].count("AB")
    if s[i][0]=="B":
        i +=1
    if s[i][-1]=="A":
        f +=1
    if s[i][0]=="B" and s[i][1]=="A":
        both+=1
        i-=1
        f-=1

if both!=0:
    if i==0 and f==0:
        print(m+both+min(i,f)-1)
    else:
        print(m+both+min(i,f))

else:
    print(min(i,f))

Submission status: Runtime Error

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

cnt = 0
BA = 0 # 'B~A'
lA = 0 # last 'A'
fB = 0 # first 'B'

for i in S:
  c = i.count('AB')
  # count 'B~*', 'B~A' '*~A'
  if i.find('B') == 0 and i.rfind('A') == len(i)-1:
    BA += 1
  elif i.find('B') == 0:
    fB += 1
  elif i.rfind('A') == len(i)-1:
    lA += 1
  cnt += c

# lA_fB = min(lA, fB)  
# r = min(abs(lA - fB), BA)
# n = max(0, (BA -r) // 2)

if lA_fB > 0:
  cnt += lA_fB -1
  if lA > 0:
    cnt += 1
    lA -= 1
  if fB > 0:
    cnt += 1
    fB -= 1

cnt += min(fB, lA)
print(cnt)

Submission status: Runtime Error

Solution code:
n=int(input())
count=countA=countB=countAB=0
for i in range(n):
    s=input()
    if "AB" in s:
        count+=1
    if s[-1]=="A":countA+=1
    if s[0]=="B":countB+=1
    if s[-1]=="A" and s[0]=="B":countAB+=1
print(countAB-1 if countA=countB=0 and countAB>0 else min(countA,countB)+countAB)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;
string a[10005];
int check[10005],n;
void DFS1(int i,int &res,int start){
	int chon=0;
    for(int j=1;j<=n;j++){
        if(check[j]==0){
        	
            if(start==0){
            	if((a[i][a[i].size()-1]=='A')&&((a[j][0]=='B'))){
                    res++;
                    cout<<i<<" th1 "<<j<<endl;
                    check[j]=1;
	                chon=j;
                }
                else{
	            	if((a[i][a[i].size()-1]!='A')&&((a[j][0]=='B'))){
	                	continue;
	                }
	                check[j]=1;
	                chon=j;
	                
                }
                break;

            }
            else{
            	if((a[i][0]!='B')&&((a[j][a[j].size()-1]=='A'))){
                    continue;
                }
            	if((a[j][0]=='B'))
            		continue;
                if((a[i][0]=='B')&&((a[j][a[j].size()-1]=='A'))){
                    res++;
                    cout<<i<<" th2 "<<j<<endl;
                }
                check[j]=1;
                chon=j;
                break;
            }
            
        }
    }
    if(chon!=0){
    	cout<<i<<" "<<chon<<endl;
    	DFS1(chon,res,start);
    }
}
void DFS(int i,int &res,int start){
	int chon=0;
    for(int j=1;j<=n;j++){
        if(check[j]==0){
        	
            if(start==0){
            	if((a[i][a[i].size()-1]=='A')&&((a[j][0]=='B'))){
                    res++;
                    check[j]=1;
	                chon=j;
	                break;
                }
                

            }
            else{
                if((a[i][0]=='B')&&((a[j][a[j].size()-1]=='A'))){
                    res++;
                    check[j]=1;
	                chon=j;
	                break;
                }
            }
        }
    }
    if(chon!=0){
    	//cout<<i<<" "<<chon<<endl;
    	DFS(chon,res,start);
    }
}
int main()
{
    int ans=0;
    cin>>n;
    vector<int>v;
    int start=0;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        if((a[i][a[i].size()-1]=='A')||(a[i][0]=='B')){
            v.push_back(i);
        }
        for(int j=1;j<a[i].size();j++){
            if((a[i][j]=='B')&&(a[i][j-1]=='A')){
                ans++;
            }
        }
    }
    //cout<<start<<endl;
	for(int i=0;i<v.size();i++){
		int start=v[i];
        if(check[start]==0){   
        	check[start]=1;
	    	if(a[start][a[start].size()-1]=='A'){
	            DFS(start,ans,0);
	        }
	    	if(a[start][0]=='B'){
	            DFS(start,ans,1);
	        }
        }
    }
    cout<<ans<<endl;
}

Submission status: Runtime Error

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

ans = 0
start_b = 0
end_a = 0
ab = 0

for i in range(n):
    for j in range(len(S) - 1):
        if S[i][j] + S[i][j + 1] == 'AB':
            ans += 1

    if S[i][0] == 'B' and S[i][-1] == 'A':
        ab += 1
        continue 
    if S[i][0] == 'B':
        start_b += 1
    if S[i][-1] == 'A':
        end_a += 1
    

if ab > 0:
    ans += ab - 1
    if start_b > 0:
        ans += 1
        start_b -= 1
    if end_a > 0:
        ans += 1
        end_a -= 1
        
ans += min(start_b, end_a)

print(ans)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
n=int(input())
s=list(input() for _ in range(n))
m,i,f=0,0,0

for i in range(n):
    m +=s[i].count("AB")
    if s[i][0]=="B":
        i +=1
    if s[i][-1]=="A":
        f +=1

if min(i,f)!=n:
    print(m+min(i,f))
else:
    print(m+min(i,f)-1)

Submission status: Runtime Error

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

# 先頭が B ではなく、末尾が A な文字列
TxBA = [s[n] for n in range(N) if s[n][0] != "B" and s[n][-1] == "A"]

# 先頭が B で、末尾が A な文字列
TBBA = [s[n] for n in range(N) if s[n][0] == "B" and s[n][-1] == "A"]

# 先頭が B で、末尾が A ではない文字列
TBBx = [s[n] for n in range(N) if s[n][0] == "B" and s[n][-1] != "A"]

str = ""

while (len(TxBA)):
    str += TxBA.pop()
    while (len(TBBA)):
        str += TBBA.pop()
    if (len(TBBx)):
        str += TBBx.pop()

while (len(TBBx)):
    str += TBBx.pop()

while (len(ss)):
    str += ss.pop()

print(str.count("AB"))

Submission status: Runtime Error

Solution code:
N = int(input())
s = []
for i in range(N):
	s.append(input())
l = list(itertools.combinations(s,len(s))
m = []
for j in range(N):
	new_s = "".join(s[i])
    num = new_s.count("AB")
    m.append(num)
print(max(m))

Submission status: Runtime Error

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
count+=min(ap,bp)
if abc>0:
    count+=abc-1
    pp-=abc-1
    if ap>0 or bp>0:
        count+=1
print(count)

Submission status: Runtime Error

Solution code:
N = int(input())
head_B_list = {}
bottom_A_list = {}
answer = 0

for i in range(N):
    str = input()
    if(str[0] == "B"):
        head_B_list[i] = 1
    if(str[-1] == "A"):
        bottom_A_list[i] = 1
    while "AB" in str:
        answer += 1
        str = str.replace("AB", "", 1)
if(len(head_B_list) < len(bottom_A_list)):
    for B in head_B_list.keys():
        del_A = -1
        for A in bottom_A_list:
            if(B != A):
                del_A = A
                answer += 1
                break
        if del_A >= 0:
            bottom_A_list.pop(del_A)
else:
    head_B_list.popitem()
    for A in bottom_A_list.keys():
        del_B = -1
        for B in head_B_list:
            if(A != B):
                del_B = B
                answer += 1
                break
        if del_B >= 0:
            head_B_list.pop(del_B)
print (answer)

Submission status: Runtime Error

Solution code:
def hantei(s):
  if s[0] == "B" and s[-1] == "A":
    return 0
  elif s[0] == "B":
    return 1
  elif s[-1] == "A":
    return 2
  else return 3
  
N = int(input())
num = [0, 0, 0, 0]
NUM = 0
for _ in range(N):
  S = input()
  NUM += S.count("AB")
  num[hantei(S)] += 1 
print(NUM + min(num[1],num[2]) + num[0]-1 + min(abs(num[1] - num[2]), num[0]))

Submission status: Runtime Error

Solution code:
def hantei(s):
  if s[0] == "B" and s[-1] == "A":
    return 0
  elif s[0] == "B":
    return 1
  elif s[-1] == "A":
    return 2
  else return 3
  
N = int(input())
num = [0, 0, 0, 0]
NUM = 0
for _ in range(N):
  S = input()
  NUM += S.count("AB")
  num[hantei(S)] += 1 
print(NUM + min(num[1],num[2]) + num[0]-1 + min(abs(num[1] - num[2]), num[0]))

Submission status: Runtime Error

Solution code:
N=int(input())
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 headB == pair and tail_A == pair))

Submission status: Runtime Error

Solution code:
ans=0
a_number=0
b_number=0
double=0
for i in range(N):
    ans+=mojicount(A[i],'AB')
    
    if A[i][0]=='B':
        b_number+=1
    if A[i][-1]=='A':
        a_number+=1
        if A[i][0]=='B':
            double=+1


    
print(ans+min(a_number,b_number)-double)

Submission status: Runtime Error

Solution code:
N = int(input())
s_list = []
count = 0
n, m, l = 0, 0, 0

for i in range(N):
  s = input()
  s_list.append(s)
  count += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    n += 1
    continue
  elif s[-1] == 'A':
    m += 1
  elif s[0] == 'B':
    l += 1

if n < m and n < l:
  print(int(count + 2 * n + min(m - n, l - n)))
elif n > m and n > l:
  print(int(count + 2 * (n - max(m, l) + m + l)
else:
  print(int(count + min(n, m) + min(n, l)))

Submission status: Runtime Error

Solution code:
import numpy as np
N = int(input())
ss = [input() for _ in range(N)]

num_ab = 0
pres = []
posts = []
ss2 = []
for s in ss:
    
    while True:
        if len(s) == 0:
            break
        if len(s) > 1:
            if s[0:2] == 'AB':
                s = s[2:]
                num_ab += 1
            else:
                break
        else:
            break
    while True:
        if len(s) == 0:
            break
        if len(s) > 1:
            if s[-2:] == 'AB':
                s = s[:-2]
                num_ab += 1
            else:
                break
        else:
            break
#     print(s)
    if len(s) > 0:
        if s[0] == 'A':
            pres.append(1)
        elif s[0] == 'B':
            pres.append(-1)
        else:
            pres.append(0)
        if s[-1] == 'A':
            posts.append(1)
        elif s[-1] == 'B':
            posts.append(-1)
        else:
            posts.append(0)
    else:
        pres.append(0)
        posts.append(0)
        
    ss2.append(s)

i = 0
while i < len(pres):
    if pres[i] == 0 and posts[i] == 0:
        ss2.pop(i)
        pres.pop(i)
        posts.pop(i)   
        i -= 1
    i += 1
    


def query(pre_q = False, post_q = False):
    for i in range(len(ss2)):
        if pres[i] == pre_q and posts[i] == post_q:
            return i
    return -1

s = ""

ind = query(0, 1)
if ind == -1:
    ind = query(1, 1)
if ind == -1:
    ind = query(-1, 1)
if ind == -1:
    ind = 0
s += ss2[ind]
ss2.pop(ind)
pres.pop(ind)
posts.pop(ind)


while True:

    ind = query(-1, 1)
    if ind == -1:
        ind = query(-1, 0)
    if ind == -1:
        ind = query(-1, -1)
    if ind == -1:
        ind = 0

    s += ss2[ind]
    ss2.pop(ind)
    pres.pop(ind)
    posts.pop(ind)
    
    if len(ss2) == 0:
        break

while True:
    i = s.find('AB')
    if i >= 0:
        num_ab += 1
        s = s[i + 2:]
    else:
        break

print(num_ab)

Submission status: Runtime Error

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 (x[-1] == "A")&(x[0] == "B"):
    d += 1
if (a == b)&(a == d):
  c = a-1
else:
  c = min(a,b)
print(ab+c)

Submission status: Runtime Error

Solution code:
N = int(input())

S = []
for _ in range(N):
    s = input()
    S.append(s)
    
sub_strs = S[:]

count_ab = 0
for s in sub_strs:
    count_ab += s.count('AB')
    
count_ba = 0
count_xa = 0
count_bx = 0

for s in sub_strs:
    if s[0] == 'B' and s[-1] == 'A':
        count_ba += 1
    if s[0] != 'B' and s[-1] == 'A':
        count_xa += 1
    if s[0] == 'B' and s[-1] != 'A':
        count_bx += 1



ans = 0
ans += count_ab

# 前後にくっつける
tmp = (min(count_xa, count_bx), count_ba)
ans += tmp * 2

# 更新
count_ba = count_ba - tmp
count_xa = count_xa - tmp
count_bx = count_bx - tmp



ans += count_ba - 1

if count_xa > 0 or count_bx > 0:
    ans += 1




print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
s = [input() for i in range(N)]
ABcount = 0
for i in s:
    ABcount += i.count("AB")
bvva = 0
bvvv = 0
vvva = 0
for i in s:
    if i[0] == "B" and i[-1] == "A":
        bvva += 1
    elif i[0] == "B":
        bvvv += 1
    elif i[-1] == "A":
        vvva += 1
if vvva != 0:
    if bvvv != 0:
        print(ABcount+bvva+1+(min(vvva-1,bvvv-1)))
    else:
        print(ABcount+bvva)
else:
    if bvvv != 0:
        print(ABcount+bvva)
    else:
        print(max(ABcount+bvva-1),0)

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
coo= 0

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

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

if ss == coo:
    if ss == b:
        if ss == a:
            if ss != 0:
                ss -= 1
print(re + ss)

Submission status: Runtime Error

Solution code:
N=int(input())
A,B=0
for i in range(N):
  X=input()
  if X[0]== "B":
    B+=1
    if X[-1]=="A":
      A+=1
      Y=X.count("AB")
M=min(A,B)
count=M+Y
print(count)

Submission status: Runtime Error

Solution code:
import copy
n = int(input())
strings = [input() for _ in range(n)]
ta_hb = list(filter(lambda s: s[-1] == "A" and s[0] == "B", strings))
for s in ta_hb:
    strings.remove(s)
tail_a = list(filter(lambda s: s[-1] == "A", strings))
for s in tail_a:
    strings.remove(s)
head_b = list(filter(lambda s: s[0] == "B", strings))
for s in head_b:
    strings.remove(s)
result = ""
if 0 < len(tail_a) and 0 < len(head_b):
    result = tail_a.pop(0) + "".join(ta_hb) + head_b.pop(0)
elif 0 < len(tail_a):
    result = tail_a.pop(0) + "".join(ta_hb)
elif 0 < len(head_b):
    result = join(ta_hb) + head_b.pop(0)
ab = []
l = copy.deepcopy(zip(tail_a, head_b))
for a,b in l:
    ab.append(a+b)
    tail_a.remove(a)
    head_b.remove(b)
result = result + "".join(ab) + "".join(strings) + "".join(tail_a) + "".join(head_b)
print(result.count("AB"))