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 sys
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
ans = 0
a=0
b=0

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

ans += min(n-1,a,b)
print(ans)

Submission status: Wrong Answer

Solution code:
n,*s=map(str,open(0).read().split())
b=sum([c.startswith('B')for c in s])
a=sum([c.endswith('A')for c in s])
e=a if b>=a else b
if e==int(n):e-=1
if any([c.startswith('B')and c.endswith('A')for c in s]):e-=1
print(sum([c.count('AB')for c in s])+e)

Submission status: Wrong Answer

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

cnt = 0
cntBA = 0
cntA = 0
cntB = 0
for i in s:
    for j in range(len(i) - 1):
        if i[j:j + 2] == "AB":
            cnt += 1
    #print(i)
    if i[0] == "B" and i[-1] == "A":
        cntBA += 1
    elif i[0] == "B":
        cntB += 1
    elif i[-1] == "A":
        #print(123)
        cntA += 1

#print(cnt, cntA, cntB, cntBA)
ans = cnt + max(0, cntBA - 1)
ans += min(cntA, 1)
cntA -= 1
ans += min(cntB, 1)
cntB -= 1
ans += max(min(cntA, cntB), 0)

print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
result=0
fb=0# first is b
la=0# last is a
for i in range(N):
    s=input()
    result+=s.count('AB')
    if s[0]=="B":
        fb+=1
    if s[-1]=="A":
        la+=1


mn=min(fb,la)
if mn==N:
    mn-=1
    
result+=mn
print(result)

Submission status: Wrong Answer

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


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

    return


def main():

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N=int(input())
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)
print(ans)

Submission status: Wrong Answer

Solution code:
def task_c():
    n = int(input())
    sss = [input().strip() for _ in range(n)]
    
    c_first_b = len([ss for ss in sss if ss[:1] == 'B'])
    c_last_a = len([ss for ss in sss if ss[-1:] == 'A'])
    c_include_ab = len([ss for ss in sss if 'AB' in ss])
    print(min(c_first_b, c_last_a) + c_include_ab)
    
task_c()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

ct_a=0
ct_b=0
ct_ab=0

for i in range(N):
    if s[i][0]=='B':
        ct_b+=1
    if 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
    
print(ct_ab+min(ct_a,ct_b))

Submission status: Wrong Answer

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

ab, a, b = 0, 0, 0
for s in S:
    if s[0] == "B":
        b += 1
    if s[-1] == "A":
        a += 1
    ab += s.count("AB")
print(ab + (a + b) // 2)

Submission status: Wrong Answer

Solution code:
N = int(input())
L = [input() for _ in range(N)]
ctrAB = 0
lastA = 0
firstB = 0
for s in L:
    if s[0] == 'B':
        firstB += 1
    if s[-1] == 'A':
        lastA += 1
    ctrAB += s.count('AB')
print(ctrAB + min(lastA,firstB))

Submission status: Wrong Answer

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


def solve(N: int, S: "List[str]"):
    ret = 0
    a = 0
    b = 0
    ab = 0
    for s in S:
        i = 0
        for i in range(len(s) - 1):
            if s[i:i+2] == 'AB':
                ret += 1
        if s[0] == 'B':
            a += 1
        if s[-1] == 'A':
            b += 1
        if s[0] == 'B' and s[-1] == 'A':
            ab += 1
    ret += min(a, b)
    if a == b and a == ab:
        ret -= 1
    print(ret)
    return


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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())

res = 0
bhogea = 0
bhoge = 0
hogea = 0

for i in range(N):
    s = input()
    res += s.count('AB')
    if s[0] == 'B' and s[-1:] == 'A':
        bhogea += 1
    elif s[0] == 'B':
        bhoge += 1
    elif s[-1:] == 'A':
        hogea += 1

res = res + max(0, bhogea - 1)
res = res + min(bhoge, hogea)

if (bhoge != hogea) and (bhogea != 0):
    res = res + 1

print(res)

Submission status: Wrong Answer

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

cnt1=0
B_Start=0
A_End=0

for i in range(N):
    cnt1 += S[i].count("AB")
    if S[i][0] == "B":
        B_Start += 1
    if S[i][-1] == "A":
        A_End += 1

print(cnt1 + min(B_Start,A_End))

Submission status: Wrong Answer

Solution code:
#C
N = int(input())
t = [''] * N
num = 0
for k in range(0, N):
    s = str(input())
    t[k] = s
    num += s.count('AB')

counts = []
for i in range(0, 3):
    count = num
    for j in range(0, 3):
        if i == j:
            pass
        if t[i][-1] == 'A' and t[j][0] == 'B':
            count += 1
    counts.append(count)
print(max(counts))

Submission status: Wrong Answer

Solution code:
N = int(input())
ABc = 0
Ac = 0
Bc = 0
for i in range(N):
	s = input()
	ABc += s.count("AB")
	if s[0] == "B":
		Bc += 1
	if s[-1] == "A":
		Ac += 1

print(ABc + min(Ac, Bc))

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for _ in [0]*N]
ni = [0]*N
for i,si in enumerate(s):
    for j,c in enumerate(si[:-1]):
        if c == "A" and si[j+1] == "B":
            ni[i] += 1
cntA,cntB,cntAB = 0,0,0
for si in s:
    if si[0]=="B" and si[-1]=="A":
        cntAB += 1
    elif si[0]=="B":
        cntB += 1
    elif si[-1]=="A":
        cntA += 1
ans = sum(ni) + cntAB + min(cntA,cntB) - (cntA==0 and cntB==0)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
num = 0
a = 0
b = 0
ba = 0

for i in range(N):
    x = (input())
    num = num + x.count('AB')
    if x[0] == 'B':
        b = b + 1
        if x[-1] == 'A':
            ba = ba +1
    if x[-1] == 'A':
        a = a + 1

if ba == b and a == b:
    print(num+b-1)
else:
    print(num+min(a,b))

Submission status: Wrong Answer

Solution code:
import sys

def main():
    input = sys.stdin.readline
    N = int(input())
    ans = 0
    last_a = 0
    first_b = 0
    for _ in range(N):
        s = str(input().strip())
        if 'AB' in s:
            ans += 1

        if s[0] == 'B' and last_a > 0:
            ans += 1
            last_a -= 1
            s = 'b' + s

        if s[-1] == 'A' and first_b > 0:
            ans += 1
            first_b -= 1
            s = s + 'a'

        if s[0] == 'B':
            first_b += 1

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

    return ans


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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
#
import itertools
from collections import Counter
from collections import defaultdict
import bisect

def main():
    N = int(input())
    inside = 0

    top_B = 0
    tail_A = 0
    both = 0
    for _ in range(N):
        s = input()
        inside += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A':
            both += 1
        else:
            if s[0] == 'B':
                top_B += 1
            elif s[-1] == 'A':
                tail_A += 1
    # print('inside = {}, top b = {}, tail a = {}, both = {}'.format(inside, top_B, tail_A, both))
    ans = inside

    if both > 0:
        if tail_A == 0:
            tail_A += 1
            both -= 1
        elif top_B == 0:
            top_B += 1
            both -= 1

    while both > 0 and top_B > 0 and tail_A > 0:
        ans += 2
        both -= 1
        tail_A -= 1
        top_B -= 1

        if both > 0:
            if tail_A == 0:
                tail_A += 1
                both -= 1
            elif top_B == 0:
                top_B += 1
                both -= 1

    while top_B > 0 and tail_A > 0:
        ans += 1
        tail_A -= 1
        top_B -= 1

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
count_A_right = 0
count_B_left  = 0
AB_count = 0

for _ in range (N):
    S = input()
    if S[0] == 'B':
        count_B_left +=1
    if S[-1] == 'A':
        count_A_right +=1
    for i in range (len(S)-1):
        if S[i:i+2] == 'AB':
            AB_count +=1
 
print(AB_count+min(count_A_right,count_B_left))

Submission status: Wrong Answer

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

ans = 0
A_count = 0
B_count = 0
for i in range(N):
	ans += s[i].count("AB")
	if s[i][0] == "B":
		B_count += 1
	if s[i][-1] == "A":
		A_count += 1
ans += min(A_count,B_count)

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [0 for i in range(N)]
for i in range(N):
    s[i] = input()
count = 0
Aowari = 0
Bhazimari = 0
for i in range(N):
    count += s[i].count('AB')
    if s[i][0] == 'B':
        Bhazimari += 1
    if s[i][-1] == 'A':
        Aowari += 1
minAB = min(Aowari, Bhazimari)
if minAB == N:
    minAB = N-1
print(count+minAB)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

end_a = 0
start_b = 0
end_a_start_b = 0
for s in strings:
    if s[0] == 'B':
        start_b += 1
    if s[-1] == 'A':
        end_a += 1
    if s[0] == 'B' and s[-1] == 'A':
        end_a_start_b += 1

ans = max(min(end_a, start_b),
          min(start_b, end_a))

for s in strings:
    ans += s.count('AB')

print(ans)

Submission status: Wrong Answer

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

cnt = 0
judge = 0
for i in range(n):
    for j in range(len(s[i])):
        if j != len(s[i]) - 1:
            if s[i][j] == "A":
                judge = 1
            if judge == 1 and s[i][j] != "A":
                if s[i][j] == "B":
                    cnt += 1
                    judge = 0
                else:
                    judge = 0
        else:
            judge = 0
cnt_a = 0
cnt_b = 0
for i in range(n):
    len_s = len(s[i])
    if s[i][len_s - 1] == "A":
        cnt_a += 1
    if s[i][0] == "B":
        cnt_b += 1
        
print(cnt + min(cnt_a, cnt_b))

Submission status: Wrong Answer

Solution code:
N = int(input())

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

if a == 0:
    a = N-1
if b == 0:
    b = N-1
#print(a, b)
print(count+min([a, b, N-1]))

Submission status: Wrong Answer

Solution code:
c = int(input())
res = 0
a = 0
b = 0
lines = []
for i in range(c):
    s = input()
    res += len(s.split('AB')) - 1
    b += 1 if s.startswith('B') else 0
    a += 1 if s.endswith('A') else 0

if c == a and c == b:
    a -= 1

res = res + min(a, b)
print(res)

Submission status: Wrong Answer

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+=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: Wrong Answer

Solution code:
x = int(input())
a = 0
b = 0
c = 0
bun = []
for p in range(x):
    bun = input()
    if bun[0] == "B":
        b +=1
    if bun[len(bun)-1] == "A":
        a += 1
    for k in range(len(bun)-1):
        if bun[k] == "A":
            if bun[k+1] == "B":
                c += 1
if a == x:
    a = a-1
if a < b:
    print(a+c)
else:
    print(b+c)

Submission status: Wrong Answer

Solution code:
N = int(input())
counter = 0
listA = []
listB = []
for i in range(N):
    s = input()
    counter += s.count('AB')
    if s[-1] == 'A':
        listA += [i]
    if s[0] == 'B':
        listB += [i]
if len(listA) == N and len(listB) == N:
    counter += N-1
elif listA == listB:
    counter += len(listA)-1
else:
    counter += min(len(listA), len(listB))
print(counter)

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
l = 0
r = 0
for _ in range(N):
    s = str(input())
    if "AB" in s:
        ans += 1
    if s[-1] == "A":
        r += 1
    if s[0] == "B":
        l += 1
ans += (r+l) // 2
print(ans)

Submission status: Wrong Answer

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()
print(temp_sum + min(N - 1,A_or_B_count[0] + AB_count,A_or_B_count[1]))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

import sys
from collections import deque, Counter
import bisect
import math
from itertools import accumulate, product, permutations, combinations, groupby
from fractions import gcd 
import heapq
sys.setrecursionlimit(10**6)
#input = sys.stdin.readline #文字列入力のときは注意

#n = int(input())
#s = input()
#a = [int(i) for i in input().split()]
#m = [[int(i) for i in input().split()] for j in range(n)] # 縦「n」行

n = int(input())
s = [input() for j in range(n)] # 縦「n」行
ans = 0
ba = 0
bc = 0
ca = 0
cc = 0
for ss in s:
    if ss[0]=="B" and ss[-1]=="A":
        ba += 1
    elif ss[0]=="B":
        bc += 1
    elif ss[-1]=="A":
        ca += 1
    else:
        cc += 1
    for i in range(len(ss)-1):
        if ss[i] == "A" and ss[i+1] == "B":
            ans +=1
#print(ans,ba,bc,ca,cc)
ans += min(bc,ca) + ba

print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env pypy3

import math, itertools, operator
from math import *
from math import factorial as fact
from itertools import permutations, combinations
from functools import reduce
from statistics import mean, median, median_low, median_high, mode
# Before Python 3.5
from fractions import gcd

#import numpy
#import scipy, scipy.special
#from sympy import isprime, nextprime
#from sympy.ntheory import factorint

inf = float('inf')

def lcm(a, b):
    return a * b // gcd(a,b)

def perm(a, b):
    import scipy.special
    return scipy.special.perm(a, b, exact = True)

def comb(a, b):
    import scipy.special
    return scipy.special.comb(a, b, exact = True)

def dfact(n):
    import scipy.special
    return scipy.special.factorial2(n, exact = True)

def prod(l):
    return reduce(operator.mul, l)

def input_ints(inp = input, sep = ' ', conv = int):
    return map(conv, inp().split(sep = sep))

################################################################################


N = int(input())
si = [input() for i in range(N)]

n_AB = 0
n_endswithA = 0
n_startswithB = 0
for i in range(N):
    n_AB += si[i].count('AB')
    if si[i].endswith('A'):
        n_endswithA += 1
    if si[i].startswith('B'):
        n_startswithB += 1

cnt = (n_AB + min(n_endswithA, n_startswithB))
if n_endswithA == N and n_startswithB == N:
    cnt -= 1
print(cnt)

Submission status: Wrong Answer

Solution code:
n=int(input())
l=[input() for i in range(n)]
ct=0;cta=0;ctb=0;ctab=0
for i in range(len(l)):
  for j in range(len(l[i])-1):
    if l[i][j]=='A' and l[i][j+1]=='B':ct+=1
  if l[i][0]=='B' and l[i][len(l[i])-1]=='A':
    ctab+=1
    cta+=1
    ctb+=1
  elif l[i][len(l[i])-1]=='A':cta+=1
  elif l[i][0]=='B':ctb+=1
x=min(cta,ctb)
if x==10:x=9
if ctab==cta and ctab==ctb:
  print(ct+x-1)
else:
  print(ct+x)

Submission status: Wrong Answer

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

ans = 0
for ss in sss:
    ans += ss.count('AB')

num_A = numB_ = numBA = 0
for ss in sss:
    is_A = ss.endswith('A')
    isB_ = ss.startswith('B')
    if is_A:
        num_A += 1
    if isB_:
        numB_ += 1
    if is_A and isB_:
        numBA += 1

ans += min(num_A, numB_)
if num_A == numBA and num_A > 0:
    ans -= 1

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

ab = 0 #naka
a = 0 #matsubinomi
b = 0 #sentounomi
ba = 0 #ryouhou

def count(s):
    l = len(s)
    ret = 0
    for i in range(l-1):
        if s[i] == 'A' and s[i+1] == 'B':
            ret += 1
    return ret

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

Submission status: Wrong Answer

Solution code:
n=int(input())
f=0
b=0
c=0
for i in range(n):
    s=input()
    if "AB" in s:
        c+=1
    if s[0]=="B":
        b+=1
    if s[len(s)-1]=="A":
        f+=1
print(c+min(f,b))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, s: "List[str]"):
    hb = 0
    ta = 0
    ab = 0
    for ss in s:
        hb += 1 if ss[0] == 'B' else 0
        ta += 1 if ss[-1] == 'A' else 0
        ab += ss.count('AB')
    return ab + min(hb, ta)


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]"
    result = solve(N, s)
    if isinstance(result, Iterable):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

if a == 0 and b == 0:
    res += ab-1

elif a < b:
    res += a
    b -= a
    res += ab
else:
    res += b
    res += ab
print(res)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = 0
a = 0
b = 0
c = 0
for i in range(n):
    bo = input()
    if bo[0]=='B' and bo[-1]=='A':
        s+=1
    elif bo[0]=='B':
        b+=1
    elif bo[-1]=='A':
        a+=1
    
    for i in range(len(bo)-1):
        if bo[i]=='A' and bo[i+1]=='B':
            c+=1

c+=min(a,b)
k = min(a,b)
a = a-k
b = b-k
if a!=0:
    a = 1
if b!=0:
    b = 1

s = max(s-1,0)
print(c+s+a+b)

Submission status: Wrong Answer

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

count_ab = sum([s.count('AB') for s in S])
count_top_b = len([1 for s in S if s[0] == 'B'])
count_last_a = len([1 for s in S if s[-1] == 'A'])

result = count_ab + min(count_top_b, count_last_a)
print(result)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for i in range(N)]
#print(S)
a_cnt = 0
b_cnt = 0
ab_cnt = 0
for i,s in enumerate(S):
    ab_cnt += s.count("AB")
    if s[-1] == "A":
        a_cnt += 1
    if s[0] == "B":
        b_cnt += 1
if a_cnt == b_cnt == N:
    ab_cnt += min(a_cnt, b_cnt) - 1
else:
    ab_cnt += min(a_cnt, b_cnt)

print(ab_cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for _ in range(N)]
ans = 0
ac = 0
bc = 0
for st in s:
    ans += st.count('AB')
    if st[-1] == 'A':
        ac += 1
    if st[0] == 'B':
        bc += 1
print(ans + min(ac, bc))

Submission status: Wrong Answer

Solution code:
N = int(input())

ans = 0
dic = {"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
print(ans + min(dic["A"], dic["B"]))

Submission status: Wrong Answer

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

AB = 0
lastA = 0
firstB = 0
both = 0
for s in S:
  if s[-1] == 'A' and s[0] == 'B':
    both += 1
  else:
    if s[-1] == 'A':
      lastA += 1
    if s[0] == 'B':
      firstB += 1
  for i in range(len(s)-1):
    if s[i:i+2] == 'AB':
      AB += 1
x = min(lastA, firstB)
y = abs(lastA - firstB)
if y > 0:
  print(AB + min(N-1, x + both))
else:
  print(AB + min(N-1, x + both - 1))

Submission status: Wrong Answer

Solution code:
N = input()
s = []
flaga = 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
	for c in s2:
		if flaginit == 1:
			if c =='A':
				flaga = 1
			elif c =='B':
				Bstart += 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
AB += min(Aend,Bstart,N-1)
print(AB)

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[input() for _ in [0]*N]
AB=0
A=0
B=0
for s in S:
    AB+=s.count("AB")
    if s[-1]=="A":A+=1
    if s[0]=="B":B+=1
print(min([A,B,N-1])+AB)

Submission status: Wrong Answer

Solution code:
n = int(input())

ans = 0
j = 0
k = 0
for i in range(n):
    s = input()
    ans += s.count("AB")
    if(s[0] == 'B'):
        k+=1
    if(s[-1] == 'A'):
        j+=1

if(k==n and j==n):
    print(ans+min(k, j) - 1)
else:
    print(ans + min(k, j))

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
from collections import Counter

n = getN()
enda = 0
begb = 0
ab = 0
both = 0
for i in range(n):
    s = input()
    if s.startswith("B"):
        enda += 1
    if s.endswith("A"):
        begb += 1
    if s.startswith("B") and s.endswith("A"):
        both += 1
    for a, b in zip(s, s[1:]):
        if a == "A" and b == "B":
            ab += 1

ans = ab + min(enda,begb)
dec = 0
if min(enda,begb) == n:
    dec = 1
if min(enda, begb) == both:
    dec = 1
print(ans-dec)

Submission status: Wrong Answer

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

def count(s):
    p = 0
    result = 0
    while 1:
        q = s.find("AB", p)
        if q < 0:
            break
        p = q + 2
        result += 1
    return result

result = 0

la = 0
sb = 0

for s in S:
    r = count(s)
    # print("*", s, r)
    if s[-1] == "A":
        la += 1
    if s[0] == "B":
        sb += 1
    result += r

result += min(la, sb)

print(result)

Submission status: Wrong Answer

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

bstart, aend = 0, 0
ab = 0
for item in s:
    if item[0] == "B":
        bstart += 1
    if item[-1] == "A":
        aend += 1
    ab += item.count("AB")

ab += min(bstart, aend, n-1)
print(ab)

Submission status: Wrong Answer

Solution code:
N=int(input())
end_with_A=0
start_with_B=0
both=0
count=0
for i in range(N):
    s=input()
    count+=s.count("AB")
    if s[-1]=="A":
        end_with_A+=1
    if s[0]=="B":
        start_with_B+=1

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

if start_with_B==both and end_with_A==both:
    count+=(both-1)
else:
    count+=min(start_with_B,end_with_A)

print(count)

Submission status: Wrong Answer

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 same_num>0:
    ans-=1    

print(ans)

Submission status: Wrong Answer

Solution code:
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))
rr = lambda N: [ri() for _ in range(N)]
YN = lambda b: print('YES') if b else print('NO')
yn = lambda b: print('Yes') if b else print('No')
OE = lambda x: print('Odd') if x%2 else print('Even')
INF = 10**18

N=ri()
S = [0]*N
ans = 0
a = 0
b = 0
ab = 0
for i in range(N):
    s_ = input()
    S[i] = s_
    ans += s_.count('AB')
    if s_[0]=='B': b+=1
    if s_[-1]=='A': a+=1
    if s_[0]=='B' and s_[-1]=='A': ab+=1

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

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt = 0
startb = 0
enda = 0
S = []
for i in range(n):
    s = input()
    S.append(s)
    cnt += s.count('AB')
    if s[0] == 'B':
        startb += 1
    if s[-1] == 'A':
        enda += 1
print(cnt+min(startb,enda))

Submission status: Wrong Answer

Solution code:
n = int(input())


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

print(ans + min(cnt_a+cnt_ba, cnt_b+cnt_ba))

Submission status: Wrong Answer

Solution code:
import math
N=int(input())
ans=0
a,b=0,0
for i in range(N):
    s=input()
    if s[0]=="B": b+=1
    if s[-1]=="A": a+=1
    ans+=s.count("AB")

ans+=min(a,b)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = list(input()for i in range(N))
ans = 0
A,B = 0,0
for i in s:
    for j in range(len(i)-1):
        if i[j:j+2] == "AB":
            ans += 1
    if i[0] == "B":
        B += 1
    if i[-1] == "A":
        A += 1
print(ans+min(A,B))

Submission status: Wrong Answer

Solution code:
import collections as c
ip = lambda : map(int, input().split())

#################
N = int(input())
count_ab = 0
unchi = 0
clis = [0,0,0] # [f,b,f and b]

for i in range(N):
    s = input()
    if s[0] == 'B' and s[-1] == 'A':
        clis[2] += 1
    elif s[0] == 'B':
        clis[0] += 1
    elif s[-1] == 'A':
        clis[1] += 1
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            count_ab+=1
if clis[0] == 0 and clis[1] == 0:
    unchi = -1

#print(count_ab,clis)
print(min(clis[0:2]) + clis[2] + count_ab + unchi)

Submission status: Wrong Answer

Solution code:
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
n=I()
ans=0
sb=0
fa=0
sbfa=0
for i in range(n):
    ts=S()
    if ts[0]=="B" and ts[-1]!="A":
        sb+=1
    elif ts[0]!="B" and ts[-1]=="A":
        fa+=1
    elif ts[0]=="B" and ts[-1]=="A":
        sbfa+=1
    for i in range(len(ts)-1):
        if ts[i]=="A" and ts[i+1]=="B":
            ans+=1
    
if sb==fa:
    ans+=sb+max(0,sbfa-1)
else:
    ans+=min(fa,sb)+sbfa
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
a = []
ans = 0
BA = 0
B = 0
A = 0
for i in range(N):
  x = input()
  for j in range(len(x)-1):
    if x[j] == "A" and x[j+1] == "B":
      ans += 1
  if x[0] == "B" and x[-1] == "A":
    BA += 1
  elif x[0] == "B":
    B += 1
  elif x[-1] == "A":
    A += 1
ans += (BA-1)
if A != 0 and B != 0:
  ans += (min(A,B)+1)
elif A == 0 and B == 0:
  ans = ans
else:
  ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env pypy3

import math, itertools, operator
from math import *
from math import factorial as fact
from itertools import permutations, combinations
from functools import reduce
from statistics import mean, median, median_low, median_high, mode
# Before Python 3.5
from fractions import gcd

#import numpy
#import scipy, scipy.special
#from sympy import isprime, nextprime
#from sympy.ntheory import factorint

inf = float('inf')

def lcm(a, b):
    return a * b // gcd(a,b)

def perm(a, b):
    import scipy.special
    return scipy.special.perm(a, b, exact = True)

def comb(a, b):
    import scipy.special
    return scipy.special.comb(a, b, exact = True)

def dfact(n):
    import scipy.special
    return scipy.special.factorial2(n, exact = True)

def prod(l):
    return reduce(operator.mul, l)

def input_ints(inp = input, sep = ' ', conv = int):
    return map(conv, inp().split(sep = sep))

################################################################################


N = int(input())
si = [input() for i in range(N)]

n_AB = 0
n_endswithA = 0
n_startswithB = 0
for i in range(N):
    n_AB += si[i].count('AB')
    if si[i].endswith('A'):
        n_endswithA += 1
    if si[i].startswith('B'):
        n_startswithB += 1

cnt = (n_AB + min(n_endswithA, n_startswithB))
if n_endswithA == N or n_startswithB == N:
    cnt -= 1
print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
ab_count = 0
heading_b_count = 0
trailing_a_count = 0
for _ in range(N):
        s = input()
        ab_count += s.count('AB')
        if s[0] == 'B':
            heading_b_count += 1
        if s[-1] == 'A':
            trailing_a_count += 1

ans = ab_count + min(heading_b_count, trailing_a_count)
if heading_b_count == trailing_a_count and heading_b_count == N:
    ans -= 1
print(ans)