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

Solution code:
n = int(input())
s_list = [input() for _ in range(n)]
res_ab = 0
res_a = 0
res_b = 0
for s in s_list:
    res_ab += s.count('AB')
    if s[0]=='B':
        res_a += 1
    if s[-1] == 'A':
        res_b += 1

print(res_ab+min(res_a,res_b))

Submission status: Wrong Answer

Solution code:
import itertools

n = int(input())

s  = [input() for i in range(n)]
news = []
final = 0

for i in s:
  if (i[0] != 'B') and (i[-1:] != 'A'):
    if i.count('AB'):
      final += 1
  else:
    news.append(i)

    
c = itertools.permutations(news)
maxAB = 0

for v in c:
  ab = (''.join(v)).count('AB')
  if(maxAB < ab):
    maxAB = ab

print(maxAB + final)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar  1 19:29:34 2019

@author: nakamuratakayuki
"""
N = int(input())
S = []
for i in range(N):
    S.append(input())

m = 0
f = 0
b = 0
t = 0
for s in S:
    if s.startswith('B'):
        m += 1
    if s.endswith('A'):
        f += 1
    if s.startswith('B')*s.endswith('A'):
        m -= 1
        f -= 1
        b += 1
    t += s.count('AB')
ans = min(f,m)+b+t
if f == 0 and m == 0:
    ans -= 1
print(max(ans,0))

Submission status: Wrong Answer

Solution code:
class Solver:
    def __init__(self, num):
        self.n = num
        self.ans = 0
        self.check_ab = 0
        self.prefix_b = 0
        self.suffix_a = 0
        self.solve()
    
    def solve(self):
        for i in range(self.n):
            sen = input()
            if sen.find("AB") != -1:
                self.check_ab = self.check_ab + 1
            if sen[0] == "B":
                self.prefix_b = self.prefix_b + 1
            if sen[-1] == "A":
                self.suffix_a = self.suffix_a + 1
        
        if self.prefix_b > self.suffix_a:
            self.ans = self.suffix_a + self.check_ab
        else:
            self.ans = self.prefix_b + self.check_ab

        print(str(self.ans))

def main():
    n=int(input())
    Solver(n)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#coding: utf-8
N = int(input())
ans = 0
l_B = 0
r_A = 0
lbra = 0
for _ in range(N):
	tmp = input()
	ans += tmp.count("AB")
	if tmp[0] == "B":
		if tmp[-1] == "A":
			lbra += 1
		else:
			l_B += 1
	elif tmp[-1] == "A":
		r_A += 1
l = [l_B, r_A, lbra]
l.sort()
if abs(l_B - r_A) > 0:
	ans += lbra + min(l_B, r_A) + 1
else:
	ans += lbra + min(l_B, r_A)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
ab = a_end = b_top = b_a = 0
for i in range(n):
    s = input()
    if 'AB' in s:
        ab += 1
    if s[0] == 'B' and s[len(s)-1] == 'A':
        b_a += 1
    elif s[0] == 'B':
        b_top += 1
    elif s[len(s)-1] == 'A':
        a_end += 1
mi = min(a_end,b_top,b_a)
ans1 = ab+ 2*mi
if b_a > 0:
    ab += b_a-1
    b_top += 1
    a_end += 1
ans2 = ab+min(a_end,b_top)
print(max(ans1,ans2))

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:
    if none_count == n:
        print(count + right_a_count)
    else:
        print(count + right_a_count + 1)
else:
    print(count + left_b_count)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
last_a = 0
first_b = 0
both_ab = 0
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':
    both_ab+=1
if last_a == first_b and last_a > 0 and both_ab > 0:
	print(ans+last_a-1)
else:
	print(ans+min(last_a,first_b))

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
ans = 0
for i in range(N):
    si = input()
    s.append(si)

    ans += si.count("AB")




d = {}
d["A"] = 0
d["B"] = 0
d["all"] = 0

for i in range(N):
    if s[i][0] == "B" and s[i][-1] == "A":
        d["all"] += 1
    elif s[i][0] == "B":
        d["B"] += 1
    elif s[i][-1] == "A":
        d["A"] += 1

if d["all"] > 1:
    ans += (d["all"] - 1)
    ans += min(d["A"],d["B"]) + 1
else:
    if d["all"] == 1:
        a = min(1,d["A"],d["B"])
        ans += a*2
        d["A"] -= a
        d["B"] -= a
        d["all"] -= a
        ans += min(d["A"],d["B"])
    else:
        ans += min(d["A"],d["B"])

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
a = [str(input()) for i in range(N)]
cnt = 0
yobiflag = 0
bflag = 0
aflag = 0
aelseflag = 0
belseflag = 0
for i in range(N):
    flag = False
    if a[i][0] == "B":
        if a[i][-1] == "A":
            yobiflag += 1
        else:
            belseflag += 1
    else:
        if a[i][-1] == "A":
            aelseflag += 1

    for j in range(len(a[i])):
        # print(a[i][j])
        if a[i][j] == "B" and flag:
            cnt += 1
        flag = False

        if a[i][j] == "A":
            flag = True
if yobiflag > 0:
    if yobiflag != N:
        aelseflag += 1
        belseflag += 1
    yobiflag -= 1

# print(yobiflag)
# print(cnt)
# print(aelseflag)
# print(belseflag)
print(cnt + min(aelseflag, belseflag, ) + yobiflag)

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 == min(cnt_a,cnt_b):
    cnt-=1

print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = 0
top_b = 0
bottom_a = 0
both = 0

for i in range(N):
    s = input()
    if "AB" in s:
        cnt += 1
    if s[0] == "B":
        top_b += 1
    if s[-1] == "A":
        bottom_a += 1
    if s[0] == "B" and s[-1] == "A":
        both += 1

if top_b >= bottom_a:
    cnt += bottom_a
else:
    cnt += top_b
print(cnt)

Submission status: Wrong Answer

Solution code:
#0=R,1=G,2=B,3=3
N = int(input())
S = []
result = 0
firstB = 0
lastA = 0
BA = 0
for i in range(N):
    S.append(input())
    result += S[i].count("AB")
    if S[i][0] == "B" or S[i][len(S[i])-1] == "A":
        S[i] = S[i][0:len(S[i]):len(S[i])-1]
        if S[i] == "BA":
            BA += 1
        elif S[i][0] == "B":
            firstB += 1
        else:
            lastA += 1
if lastA == firstB:
    result += lastA
    result += int(BA>0)*(BA-1)
elif  lastA < firstB:#B*があまる
    result += lastA + int(BA>0)*(BA)

elif lastA > firstB:#*Aがあまる
    result += firstB + int(BA>0)*(BA)
print(result)

Submission status: Wrong Answer

Solution code:
import re

N = int(input())

lst = [[],[],[]]
for i in range(N):
    s = input()
    n = len(re.findall(r'AB', s))
    m = len(re.findall(r'A$', s))
    l = len(re.findall(r'^B', s))

    if m == 1 and m == l:
        lst[0].append((n, m, l))
    elif m + l > 0:
        lst[1].append((n, m, l))
    elif l > m:
        lst[1].append((n, m, l))

l0 = len(lst[0])
l1 = len(lst[1])

al = lst[0] + lst[1]
if l0==0:
    ans = sum([l[0] for l in al]) + min(sum([l[1] for l in al]), sum(l[2] for l in al))
else:
    ans = sum([l[0] for l in al])+ l0 -1 + min(1+sum([l[1] for l in lst[1]]), 1+sum(l[2] for l in lst[1]))
print(ans)

Submission status: Wrong Answer

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:
  print(ab+ab_-1)
else:
  print(ab+min([a,b]))

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for i in range(n)]
cnt = 0
a = 0
b = 0
ba = 0
for i in range(n):
    cnt += S[i].count("AB")
    if S[i].startswith("B") and S[i].endswith("A"):
        ba += 1
    elif S[i].startswith("B"):
        a += 1
    elif S[i].endswith("A"):
        b += 1
if ba >= 1:
    cnt += ba - 1
    if a >= 1:
        cnt += 1
    if b >= 1:
        cnt += 1
elif a >= 1 and b >= 1:
    cnt += 1
print(cnt)

Submission status: Wrong Answer

Solution code:
import os, sys, re, math

strs = []
for i in range(int(input())):
    strs.append(input())

cnt = 0
lastA = 0
firstB = 0
lAandfB = 0
for s in strs:
    cnt += s.count('AB')

    if s[0] == 'B' and s[-1] == 'A':
        lAandfB += 1
    elif s[-1] == 'A':
        lastA += 1
    elif s[0] == 'B':
        firstB += 1

#print('cnt = ' + str(cnt))
#print('lastA = ' + str(lastA))
#print('firstB = ' + str(firstB))
#print('lAandfB = ' + str(lAandfB))
cnt += min(lastA, firstB)
if lastA != firstB:
    cnt += lAandfB
elif lAandfB > 1:
    cnt += lAandfB - 1

print(cnt)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N=INT()
S=['']*N
for i in range(N):
    S[i]=input()

enda=0
startb=0
both=0
cntab=0
for i in range(N):
    if S[i].startswith('B') and S[i].endswith('A'):
        both+=1
    elif S[i].startswith('B'):
        startb+=1
    elif S[i].endswith('A'):
        enda+=1
    cntab+=S[i].count('AB')

cntab+=max(both-1, 0)
mnab=min(enda, startb)
cntab+=mnab
enda-=mnab
startb-=mnab
mxab=max(enda, startb)
if mxab!=0 and both!=0:
    cntab+=1
print(cntab)

Submission status: Wrong Answer

Solution code:
n=int(input())

#normal, start_b, end_a, both

kosu=0
tokushu=[0,0,0,0]

for i in range(n):
    line=input()
    switch=0
    for l in range(len(line)):
        if switch==1:
            if line[l]=='B':
                kosu+=1
            else:
                switch=0
        if line[l]=='A':
            switch=1
    
    if line[0]=='B':
        if line[-1]=='A':
            tokushu[3]+=1
        else:
            tokushu[1]+=1
    else:
        if line[-1]=='A':
            tokushu[2]+=1
        else:
            tokushu[0]+=1

#print(kosu)
#print(tokushu)
"""
if tokushu[3]>=1:
    mazu=tokushu[3]-1
    
else:
    mazu=0
"""
if tokushu[3]>=1:
    mazu=tokushu[3]-1
    sukunai=min(tokushu[1],tokushu[2])
    mazu+=(sukunai+1)
else:
    mazu=min(tokushu[1], tokushu[2])

print(kosu+mazu)

Submission status: Wrong Answer

Solution code:
n = int(input())

s = []

ans = 0

both = 0
a_a = 0
b_a = 0

for i in range(n):
	ss = input()
	#print(ss)
	if(ss[0] == "B" and ss[len(ss)-1] == "A"):
		both += 1
	elif(ss[0] == "B"):
		b_a += 1
	elif(ss[len(ss)-1] == "A"):
		a_a += 1
	while('AB' in ss):
		ans += 1
		ss = ss.replace("AB", "", 1)


while(both > 0 and a_a > 0 and b_a > 0):
	ans += 2
	both -= 1
	a_a -= 1
	b_a -= 1

while(both >0 and a_a > 0):
	both -= 1
	ans += 1

while(both >0 and b_a > 0):
	both -= 1
	ans += 1

if(both > 1):
	ans += both - 1
	both = 1

ans += min(a_a, b_a)

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':
        sentou_b += 1
    if i[-1] == 'A':
        ushiro_a += 1
    if i[0] == 'B' and i[-1] == 'A':
        ab += 1
# print(cnt)
# print(sentou_b)
# print(ushiro_a)
# print(ab)
# print('===')
if ab > 0 and sentou_b == ushiro_a:
    print(cnt+min(sentou_b, ushiro_a)-1)
else:
    print(cnt+min(sentou_b, ushiro_a))

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())
S = [input() for i in range(N)]

n_AB = 0
n_A = 0
n_B = 0
for i in range(N):
    n_AB += S[i].count('AB')
    if S[i][-1] == 'A':
        n_A += 1
    if S[i][0] == 'B':
        n_B += 1

cnt = n_AB + min(n_A, n_B)
if n_A == N and n_B == N:
    cnt -= 1
print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
a, b, ba = 0, 0, 0
ans = 0
for _ in range(n):
    s = str(input())
    if s[0] == 'B' and s[-1] == 'A':
        ba += 1
    elif s[0] == 'B':
        b += 1
    elif s[-1] == 'A':
        a += 1
    for i in range(len(s) - 1):
        if s[i: i + 2] == 'AB':
            ans += 1
tmp = 0
for i in range(min(a, ba) + 1):
    bai = ba - i
    for j in range(min(b, bai) + 1):
        baj = bai - j
        tmp = max(tmp, i + j + max(baj - 1, 0) + min(a, b))
ans += tmp
print(ans)

Submission status: Wrong Answer

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

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
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
    for j in range(len(s[i])-1):
        if s[i][j]=="A" and s[i][j+1]=="B":
            sab+=1
print(sab+cntAB+min(cntA,cntB))

Submission status: Wrong Answer

Solution code:
n =int(input())
c=0
ab=0
nb=0
an=0
ica=0
icb=0

for i in range(n):
    a = input().split()
    c += a[0].count('AB')
    if a[0][-1:] == 'A':
        ica = 1
    if a[0][:1] == 'B':
        icb = 1
    if ica == 1 and icb == 1:
        ab+=1
    elif ica == 0 and icb == 1:
        nb+=1
    elif ica == 1 and icb == 0:
        an+=1
   
        
if an > 0:
    an-=1
    c += ab
    if nb > 0:
        nb -= 1
        c+=1
elif ab > 0:
    ab-=1
    c += ab
    if nb > 0:
        nb -= 1
        c+=1

d = 0
if nb>0 and an>0:
    if nb>an:
        d = an
    else:
        d=nb
    
c += d

print(c)

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

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

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

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

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
max_AB = 0
max_A = 0
max_B = 0
max_J = 0

for i in range(N):
    s = input()
    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            max_AB += 1
    if s[len(s)-1] == 'A' and s[0] == 'B':
        max_J += 1
    elif s[len(s)-1] == 'A':
        max_A += 1
    elif s[0] == 'B':
        max_B += 1
if max_A == 0 and max_B == 0:
    print(max_AB)
else:
    max_A += max_J
    max_B += max_J
    if max_A > max_B:
        max_AB += max_B
    else: max_AB += max_A
    print(max_AB)

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:
    if none_count == n:
        print(count + right_a_count)
    else:
        print(count + right_a_count + 1)
else:
    print(count + left_b_count)

Submission status: Wrong Answer

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

count = 0
a = 0
b = 0
both = 0

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

if a >= both and b >= both:
    ans = count + both * 2 + min(a - both, b - both)
elif a < both and b >= both:
    ans = count + a * 2 + min(b, both) + both - min(b, both)
elif a >= both and b < both:
    ans = count + b * 2 + min(a, both) + both - min(a, both)
else:
    ans = count + min(a, b) * 2 + min(max(a, b) - min(a, b), both) + both - min(max(a, b) - min(a, b), both)

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

debug = False

def log(text):
    if debug:
        print(text)

def parse_input(lines_as_string = None):

    global debug
    lines = []
    if lines_as_string is None:
        debug = False
        lines.append(input())
        n = int(lines[0])
        for i in range(n):
            lines.append(input())
    else:
        debug = True
        lines = [e for e in lines_as_string.split("\n")][1:-1]
        n = int(lines[0])


    s = lines[1:]

    return (n, s)


def solve(n, s):

    count = 0
    count_a = 0
    count_b = 0
    count_c = 0
    for w in s:
        count = count + w.count("AB")
        if w[-1] == "A" and w[0] != "B":
            count_a = count_a + 1
        if w[-1] != "A" and w[0] == "B":
            count_b = count_b + 1
        if w[-1] == "A" and w[0] == "B":
            count_c = count_c + 1

    count = count + min(count_a, count_b)

    if count_c >= 2:
        count = count + count_c - 1 
     
    d = abs(count_a - count_b)
    if count_c >= 1 and d >= 1:
        count = count + 1


    return count


def main():
    # 出力

    print("%s" % solve(*parse_input()))

if __name__ == '__main__':

    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
c = 0
a = 0
b = 0
d = 0
for i in range(n):
    k = input()
    if k[0] == "B":
        if k[-1] == "A":
            d += 1
        else:
            b += 1
    elif k[-1] == "A":
        a += 1

    c += k.count("AB")
    
print(0)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
counter = 0
startWithB = 0
endWithA = 0
both = 0


for i in range(n):
    counter += s[i].count("AB")
    if s[i][0] == "B":
        if s[i][-1] == "A":
            both += 1
        else:
            startWithB += 1
    elif s[i][-1] == "A":
        endWithA += 1

print(counter, startWithB, endWithA, both)

dif = abs(startWithB - endWithA)
if dif > both:
    print(min(startWithB + both, endWithA + both)+counter)
else:
    print(max(startWithB, endWithA) + both - dif + counter)

Submission status: Wrong Answer

Solution code:
n = int(input())
count1 = 0
count2 = 0
count3 = 0
for i in range(n):
	s = input()
	if s[0] == "B":
		count2 += 1
	if s[len(s)-1] == "A":
		count3 += 1
	for t in range(len(s)-1):
		if s[t] == "A" and s[t+1] == "B":
			count1 += 1
if count2 != count3:
	print(count1 + min(count2, count3))
else:
	print(count1 + count2)

Submission status: Wrong Answer

Solution code:
N=int(input())
a1=0
a2=0
c1=0
c2=0
ans=0
m=0
for _ in range(N):
    s=input()
    ans+=s.count("AB")
    if s[0]=="A":
        a1+=1
    if s[-1]=="A":
        a2+=1
    if s[0]=="B":
        c1+=1
    if s[-1]=="B":
        c2+=1
    
print(ans+min(a2,c1))

Submission status: Wrong Answer

Solution code:
from sys import stdin
N=int(stdin.readline().rstrip())

data=[]
ans=0
A=0
B=0
for i in range(N):
    S=input()
    ans+=S.count("AB")
    if S[0] == "B":
        B+=1
    if S[-1] == "A":
        A+=1

print(ans+min(A,B))

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ab = 'AB'
A = 0
B = 0
C = 0
ans = 0
for s in S:
  h = 0
  if('B' == s[0]):
    h += 1
  if('A' == s[-1]):
    h += 2
  if(h ==1):
    A += 1
  elif(h == 2):
    B += 1
  elif(h == 3):
    C += 1
  a = len(s.split(ab))
  ans += (a-1)

f = False
if B > 0:
  ans += B-1
if A > 0:
  A -= 1
  ans += 1
  
if C > 0 and B > 0:
  C -= 1
  ans+=1

if A-C > 0:
  ans += C
elif C-A > 0:
  ans += A
elif C == A and C > 0:
  ans += C

print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
N = int(input())
S = [None] * N
cnt = 0
B_X = 0
X_A = 0
B_A = 0

for i in range(N):
  S[i] = input()
  cnt += S[i].count('AB')
  left_B_frag = S[i][0] == 'B'
  right_A_flag = S[i][-1] == 'A'
  if left_B_frag and right_A_flag:
    B_A += 1
  elif left_B_frag:
    B_X += 1
  elif right_A_flag:
  	X_A += 1

if B_A >= 2:
  cnt += B_A - 1
  B_A = 1
if B_X > X_A:
  cnt += B_A + X_A
else:
  cnt += B_A + B_X
# print(B_A, B_X, X_A)
print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
lef_only_ex = False
rig_only_ex = False
lef_only_ex_hold = False
rig_only_ex_hold = False
back_a = 0
forward_b = 0
inside = 0
for i in range(N):
    lef_only_ex = False
    rig_only_ex = False
    line = input()
    if line[-1] == 'A':
        back_a += 1
        rig_only_ex = True
    if line[0] == 'B':
        forward_b += 1
        lef_only_ex = True
    if line[0] == 'B' and line[-1] == 'A':
        lef_only_ex = False
        rig_only_ex = False
    if lef_only_ex and not lef_only_ex_hold:
        lef_only_ex_hold = True
    if rig_only_ex and not rig_only_ex_hold:
        rig_only_ex_hold = True

    for s in range(len(line) - 1):
        if line[s] == 'A' and line[s + 1] == 'B':
            inside += 1
print((min(back_a, forward_b) - 1 if not lef_only_ex_hold and not rig_only_ex_hold and back_a == forward_b else min(
    back_a, forward_b)) + inside)

Submission status: Wrong Answer

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

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

for i in range(a):
	s[i] = str(input())
#print(s)

B_COUNT = 0
A_COUNT = 0
AandB_COUNT = 0
AB_COUNT = 0

for i in range(a):
    char = list(s[i])
    length = len(char)
    if char[0] == "B":
        B_COUNT += 1
    if char[length-1] == "A":
        A_COUNT += 1
        if char[0] == "B":
            AandB_COUNT += 1
    for j in range(length - 1):
        if char[j] == "A" and char[j+1] == "B":
            AB_COUNT += 1
            
#print(B_COUNT,A_COUNT,AandB_COUNT,AB_COUNT)
MIN = min(B_COUNT,A_COUNT)
if MIN == AandB_COUNT and B_COUNT == A_COUNT:
    MIN -= 1

print(MIN+AB_COUNT)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)

def f(a,b,ba):
  if a>0 and ba>0:
    return 1 + f(a,b,ba-1)
  elif a>0 and b>0:
    return 1+ f(a-1,b-1,ba)
  elif ba>0 and b>0:
    return 1 + f(a,b-1,ba-1)
  elif ba>1:
    return 1 + f(a+1,b,ba-2)

  return 0

N=int(input())
a=[]
b=[]

stA=0
stB=0
stBA=0

ans=0
for x in range(N):
  z=input()
  buf=z.count("AB")
  b.append((z[0],z[-1],buf))
  ans+=buf

for z in b:
  if z[0]=="B" and z[1]=="A":
    stBA+=1
  elif z[0]=="B":
    stB+=1
  elif z[1]=="A":
    stA+=1

ans=ans+f(stA,stB,stBA)
print(ans)

Submission status: Wrong Answer

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

count=0
count_a=0
count_b=0
count_ab=0
for i in range(n):
  if(s[i][0] == 'B' and s[i][-1:] == 'A'):
    count_ab+=1
  elif(s[i][0] == 'B'):
    count_b+=1
  elif(s[i][-1:] == 'A'):
    count_a+=1

  flag=0
  for j in range(len(s[i])):
    if(flag==0 and s[i][j] == 'A'):
      flag=1
      continue
    if(flag==1 and s[i][j] == 'B'):
      count+=1
      flag=0
      continue
    if(flag==1 and s[i][j] != 'B'):
      flag=0

if(max([count_a,count_b,count_ab]) == count_ab):
  m=min([count_a,count_b])
  count+=m*2
  count_a-=m
  count_b-=m
  count_ab-=m

  count+=count_a+count_b
  count_ab-=count_a+count_b

  count+=count_ab
  if(count_a == count_b and count_a != count_ab):
    count-=1
elif(min([count_a,count_b,count_ab]) == count_ab):
  count+=count_ab*2
  count_a-=count_ab
  count_b-=count_ab
  count_ab=0

  count+=min([count_a,count_b])
else:
  m=min([count_a,count_b])
  count+=m*2

print(count)

Submission status: Wrong Answer

Solution code:
ans=0
a_end=0
b_start=0
flag_c=0

N=int(input())
for i in range(N):
    flag=0
    s=input()
    ans+=s.count("AB")
    if s[-1]=="A":
        a_end+=1
        flag+=1
    if s[0]=="B":
        b_start+=1
        flag+=1
        
    if flag==2:
        flag_c+=1

a_end-=flag_c
b_start-=flag_c

c=0
for i in range(flag_c):
    if min(a_end,b_start)==0:
        if a_end==0:
            a_end+=1
        else:
            b_start+=1
        continue
    
    if min(a_end,b_start)>0:
        a_end-=1
        b_start-=1
        c+=1

ans+=2*c
ans+=min(a_end,b_start)
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
N = int(input())
s1 = np.zeros(N)
s2 = np.zeros(N)
s3 = np.zeros(N)
co = 0
for i in range(N):
    si = str(input()).split()[0]
    #print("test",si,si[0][0],si[0][-1])
    s1[i] = (si[0]=='B')
    s2[i] = (si[-1]=='A')
    s3[i] = (s1[i]==1 and s2[i] ==1)
    co += si.count('AB')

as1 = np.sum(s1)
if as1 == N:
    as1 = N-1
as2 = np.sum(s2)
if as2 == N:
    as2 = N-1
Ans = int(co + min(as1,as2))
print (Ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

BA = 0
BX = 0
XA = 0

ans = 0

for i in range(N):
    S = input()
    if S[0] == 'B' and S[-1] == 'A':
        BA += 1
    elif S[0] == 'B':
        BX += 1
    elif S[-1] == 'A':
        XA += 1

    for a, b in zip(S, S[1:]):
        # print(a, b)
        if a == 'A' and b == 'B':
            ans += 1

# print(BA, BX, XA, ans)

ans += min(BX, XA)
if BA > 0:
    ans += BA - 1

if BA > 0 and BX != XA and max(BX, XA) > 0:
    ans += 1

print(ans)