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
# import bisect
# import math
# import itertools
# import numpy as np

# import collections

"""Template"""


class IP:
    """
    入力を取得するクラス
    """

    def __init__(self):
        self.input = sys.stdin.readline

    def I(self):
        """
        1文字の取得に使います
        :return: int
        """
        return int(self.input())

    def S(self):
        """
        1文字の取得(str
        :return: str
        """
        return self.input()

    def IL(self):
        """
        1行を空白で区切りリストにします(int
        :return: リスト
        """
        return list(map(int, self.input().split()))

    def SL(self):
        """
        1行の文字列を空白区切りでリストにします
        :return: リスト
        """
        return list(map(str, self.input().split()))

    def ILS(self, n):
        """
        1列丸々取得します(int
        :param n: 行数
        :return: リスト
        """
        return [int(self.input()) for _ in range(n)]

    def SLS(self, n):
        """
        1列丸々取得します（str
        :param n: 行数
        :return: リスト
        """
        return [self.input() for _ in range(n)]

    def SILS(self, n):
        """
        Some Int LineS
        横に複数、縦にも複数
        :param n: 行数
        :return: list
        """
        return [self.IL() for _ in range(n)]

    def SSLS(self, n):
        """
        Some String LineS
        :param n: 行数
        :return: list
        """
        return [self.SL() for _ in range(n)]


class Idea:
    def __init__(self):
        pass

    def HF(self, p):
        """
        Half enumeration
        半分全列挙です
        pの要素の和の組み合わせを作ります。
        ソート、重複削除行います
        :param p: list : 元となるリスト
        :return: list : 組み合わせられた和のリスト
        """
        return sorted(set(p[i] + p[j] for i in range(len(p)) for j in range(i, len(p))))

    def Bfs2(self, a):
        """
        bit_full_search2
        bit全探索の改良版
        全探索させたら2進数のリストと10進数のリストを返す
        :return: list２つ : １個目 2進数(16桁)  2個目 10進数
        """
        # 参考
        # https://blog.rossywhite.com/2018/08/06/bit-search/
        # https://atcoder.jp/contests/abc105/submissions/4088632
        value = []
        for i in range(1 << len(a)):
            output = []

            for j in range(len(a)):
                if self.bit_o(i, j):
                    """右からj+1番目のiが1かどうか判定"""
                    # output.append(a[j])
                    output.append(a[j])
            value.append([format(i, 'b').zfill(16), sum(output)])

        value.sort(key=lambda x: x[1])
        bin = [value[k][0] for k in range(len(value))]
        val = [value[k][1] for k in range(len(value))]
        return bin, val

    def S(self, s, r=0, m=-1):
        """
        ソート関係行います。色々な設定あります。
        :param s: 元となるリスト
        :param r: reversするかどうか 0=False 1=True
        :param m: （2次元配列）何番目のインデックスのソートなのか
        :return: None
        """
        r = bool(r)
        if m == -1:
            s.sort(reverse=r)
        else:
            s.sort(reverse=r, key=lambda x: x[m])

    def bit_n(self, a, b):
        """
        bit探索で使います。0以上のときにTrue出します
        自然数だからn
        :param a: int
        :param b: int
        :return: bool
        """
        return bool((a >> b & 1) > 0)

    def bit_o(self, a, b):
        """
        bit探索で使います。1のときにTrue出すよ
        oneで1
        :param a: int
        :param b: int
        :return: bool
        """
        return bool(((a >> b) & 1) == 1)

    def ceil(self, x, y):
        """
        Round up
        小数点切り上げ割り算
        :param x: int
        :param y: int
        :return: int
        """
        return -(-x // y)

    def ave(self, a):
        """
        平均を求めます
        :param a: list
        :return: int
        """
        return sum(a) / len(a)

    def gcd(self, x, y):
        if y == 0:
            return x
        else:
            return self.gcd(y, x % y)


"""ここからメインコード"""


def main():
    # 1文字に省略
    r, e, p = range, enumerate, print
    ip = IP()
    id = Idea()
    mod = 10 ** 9 + 7

    """この下から書いてね"""
    n = ip.I()
    ans = 0
    a = 0
    b = 0
    c = 0
    for i in range(n):
        o = input()
        res = o.count("AB")
        if res == -1:
            pass
        else:
            ans += res
        if o[-1] == 'A':
            a += 1
        if o[0] == 'B':
            b += 1
        if o[-1] == 'A' and o[0] == 'B':
            c += 1
    if min(a, b) == n:
        ans += min(a, b) - 1
    else:
        ans += min(a, b)
    if min(a, b) == c:
        ans -= 1
    p(ans)


main()

Submission status: Wrong Answer

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


def solve(n, ss):
    num_ab = sum(s.count("AB") for s in ss)
    num_both = sum(s[-1] == "A" and s[0] == "B" for s in ss)
    num_right_a = sum(s[-1] == "A" for s in ss) - num_both
    num_left_b = sum(s[0] == "B" for s in ss) - num_both
    # B --- A
    res = num_ab + num_both - 1
    if num_right_a > 0:
        num_right_a -= 1
        res += 1
    if num_left_b > 0:
        num_left_b -= 1
        res += 1
    # (X)B --- A(X)
    res += min(num_right_a, num_left_b)
    return res


def main():
    n = int(input())
    ss = [input() for _ in range(n)]
    res = solve(n, ss)
    print(res)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import math
n = int(input())

s=[]
res = 0
tmp = 0
eA=0
sB=0
eAsB=0
for i in range(n):
#	s.append(list(input()))
	s.append(input())
	tmp = s[i].count("AB")
	if tmp != 0:
		res += tmp
	if s[i][0]=="B" and s[i][-1]=="A":
		eAsB += 1
	elif s[i][-1]=="A":
		eA += 1
	elif s[i][0]=="B":
		sB += 1
		
res += min(eA, sB)
if eA < sB:
	res += min(sB-eA, eAsB)
	if (sB-eA) < eAsB:
		res += math.floor((eAsB-(sB-eA))/2)
else:
	res += min(eA-sB, eAsB)
	if (eA-sB) < eAsB:
		res += math.floor((eAsB-(eA-sB))/2)

print(res)
#print(eA)
#print(sB)
#print(eAsB)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for i in range(N)]
l1 = [s[i].count('AB') for i in range(N)]
l2 = [1 if s[i][0] == 'B' else 0 for i in range(N)]
l3 = [1 if s[i][-1] == 'A' else 0 for i in range(N)]
l4 = [l2[i]*l3[i] for i in range(N)]
if min(sum(l2),sum(l3)) == sum(l4):
    a = max(min(sum(l2),sum(l3))-1,0)
else:
    a = min(sum(l2),sum(l3))
print(sum(l1) + a)

Submission status: Wrong Answer

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
li=[]
t=0
for i in range (0,n):
  m=input()
  t=t+m.count("AB")
  li.append(list(m))
las=0
sta=0
for i in range (0,n):
  le=len(li[i])-1
  if li[i][0]=="B":
    sta=sta+1
  if li[i][le]=="A":
    las=las+1
if las==n:
  print(t+n-1)
elif sta<las:
  print(t+sta)
elif sta>las:
  print(t+las)
else:
  print(t+sta)

Submission status: Wrong Answer

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


count=0


end_A=0
start_B=0
both=0
for i in range(N):
	count+=S[i].count("AB")
	if(S[i][-1]=="A"):
		end_A+=1
	if(S[i][0]=="B"):
		start_B+=1
#	if(not (S[i][-1]=="A" and (S[i][0]=="B"))):	
	if((S[i][-1]=="A" and not S[i][0]=="B") or (not S[i][-1]=="A" and S[i][0]=="B")):
		both+=1

#print(end_A,start_B,both,count)
if(both==0):
#if(min(end_A,start_B)<=both):
	print(count+min(end_A,start_B)-1)
else:
	print(count+min(end_A,start_B))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n=int(input())
ans=0
d={"a":0,"b":0,"w":0}
for i in range(n):
    s=input()
    if s[0]=="B" and s[-1]=="A": d["w"]+=1
    elif s[0]=="B" : d["b"]+=1
    elif s[-1]=="A" : d["a"]+=1
    ans+=s.count("AB")
if d["a"]==0 and d["w"]>0:
    d["a"]=1
    d["w"]-=1
if d["b"]>0:
    ans+=1
    d["b"]-=1
d["a"]-=1
ans+=d["w"]
ans+=min(d["a"],d["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+=s.count("AB")
    if s[0]=="B":
        b+=1
    if s[len(s)-1]=="A":
        f+=1
e=0
if n==1:
    e=1
print(c+min(f,b)-e)

Submission status: Wrong Answer

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

if BA>0:
    total+=BA-1
    B+=1
    A+=1
print(total+min(A,B))

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

def main():
    input = sys.stdin.readline
    N = int(input())
    ans = 0
    q = deque()
    for _ in range(N):
        s = str(input().strip())
        for i in range(len(s)-1):
            if s[i:i+2] == 'AB':
                ans += 1

        q_ = deque()
        while len(q) > 0:
            s1 = q.popleft()

            if s[-1] == 'A' and s1[0] == 'B':
                ans += 1
                s = s + s1
            elif s[0] == 'B' and s1[-1] == 'A':
                ans += 1
                s = s1 + s
            elif s1[0] == 'B' or s1[-1] == 'A':
                q_.append(s1)

        q_.append(s)
        q = q_

    return ans


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

Submission status: Wrong Answer

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math

mod = 10**9+7

N = int(input())
s = [0 for i in range(N)]
cnt = 0
chance = False
A_cnt = 0
B_cnt = 0
BA_cnt = 0
for i in range(N):
    s[i] = str(input())
    cnt += s[i].count("AB")
    if s[i][0] == "B":
        B_cnt += 1
        if s[i][-1] == "A":
            BA_cnt += 1
    elif s[i][-1] == "A":
        A_cnt +=1

if A_cnt > 0:
    plus = min(min(A_cnt,B_cnt),N-1)
else:
    plus = BA_cnt - 1
cnt += plus

print(cnt)

Submission status: Wrong Answer

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

if f == a == b:
  print(cnt + a - 1)
else:
  print(cnt + min(a, b))

Submission status: Wrong Answer

Solution code:
n = int(input())
words = [str(input()) for i in range(n)]
counter = 0
beginb = 0
enda = 0
mix = 0
for word in words:
    for index, letter in enumerate(word):
        if index<len(word)-1:
            if word[index] == 'A' and word[index+1] == 'B':
                counter += 1
    if word[0] == "B" and word[-1] == "A":
        mix += 1
    else:
        if word[0] == "B":
            beginb += 1
        if word[-1] == "A":
            enda += 1
diff = abs(beginb-enda)
if diff-mix > 0:
    print(counter+min(beginb,enda)+mix)
else:
    mix = (mix-diff)//2
    print(counter+max(beginb,enda)+mix)

Submission status: Wrong Answer

Solution code:


def main():
    n = input()
    a = b = ab = s = 0
    for _ in xrange(n):
        st = raw_input()
        s += st.count('AB')
        if st.endswith('A'):
            a += 1
            if st.startswith('B'):
                ab += 1
        elif st.startswith('B'):
            b += 1
    if a == n:
        a -= 1
    if b == n:
        b -= 1
    if a <= b:
        print s + a
    elif ab:
        print s + min(a, b + ab - 1)
    else:
        print s + b


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    S = [input() for _ in range(N)]
    AB_count = 0
    # 元から含まれているABの計算
    head_B = 0
    tail_A = 0
    for si in S:
        # print(si.count('AB'))
        AB_count += si.count('AB')
        # print(list(si)[0], list(si)[-1])
        if list(si)[0] == 'B':
            head_B += 1
        if list(si)[-1] == 'A':
            tail_A += 1
    # 新たに作成できるABの計算
    # print(AB_count, head_B, tail_A)
    # print( tail_A == head_B == N)
    AB_count += min(head_B, tail_A)
    if tail_A == head_B == N:
        # 輪にはできないので1引く
        AB_count -= 1
    print(AB_count)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import re
N = int(input())
S = [input() for i in range(N)]
nAB = sum(map(lambda x: x.count('AB'), S))
lastB = sum(map(lambda x: x[0] == 'B', S))
firstA = sum(map(lambda x: x[-1] == 'A', S))
matchAB = sum(map(lambda x: x[0] == 'B' and x[-1] == 'A', S))
if min(lastB, firstA) == 0:
    print(nAB)
elif matchAB - min(lastB, firstA) == 0:
    print(nAB+min(lastB, firstA)-1)
else:
    print(nAB+min(lastB, firstA))

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

n = ni()
s = [ns() for _ in range(n)]

ans = 0

x = y = z = 0

for si in s:
    # 内部のABカウント
    ans += si.count('AB')

    # 右端A かつ 左端B ... Z
    if si[:1] == 'B' and si[-1:] == 'A':
        z += 1

    # 右端A ... X
    elif si[-1:] == 'A':
        x += 1

    # 左端B ... Y
    elif si[:1] == 'B':
        y += 1

if z < x and z < y:
    ans += 2*z
    ans += min(x,y) - z

else:
    ans += min(z, x)
    ans += min(z, y)

    if z > x and z > y:
        if z - max(x,y) <= max(x,y) - min(x,y):
            ans += z - max(x,y)
        else:
            ans += max(x,y) - min(x,y)
            ans += 2 * ((z - max(x,y) - (max(x,y) - min(x,y))) // 3)
            if (z - max(x,y) - (max(x,y) - min(x,y))) % 3 == 2:
                ans += 1

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = 0
B = 0
BA = 0
ans = 0
for i in range(N):
    S = input()
    for i in range(len(S) - 1):
        if S[i : i + 2] == 'AB':
            ans += 1
    if S[0] == 'B' and S[-1] == 'A':
        BA += 1
    elif S[0] == 'B':
        B += 1
    elif S[-1] == 'A':
        A += 1
    # print(S, A, B, BA, ans)

if A == 0 and B == 0:
    ans += BA - 1
else:
    ans += min(A + BA, B + BA)
    
print(ans)

Submission status: Wrong Answer

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

cnt = 0
head_b_cnt = 0
end_a_CNT = 0
head_a_end_b_cnt = 0
for word in s:
    cnt += word.count('AB')
    if word[0] == 'B':
        head_b_cnt += 1
    if word[-1] == 'A':
        end_a_CNT += 1
    if word[0] == 'B' and word[-1] == 'A':
        head_a_end_b_cnt += 1

if (head_b_cnt ==  end_a_CNT ==  head_a_end_b_cnt):
    cnt += min(head_b_cnt, end_a_CNT) - 1
else:
    cnt += min(head_b_cnt, end_a_CNT)

print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
fully_ab = 0
last_a = 0
head_b = 0
head_last_both = 0

for i in range(n):
    s = input().rstrip()
    fully_ab +=s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        head_last_both += 1
    elif s[0] == "B":
        head_b += 1
    elif s[-1] == "A":
        last_a += 1
    
assert (last_a+head_b+head_last_both <= n)
bigger = max(last_a,head_b)
lower  = min(last_a,head_b)
amari = bigger - lower

connected = max(0,head_last_both - 1)

ans = fully_ab + lower + connected

if lower > 0 and head_last_both > 0:
    if lower + connected < n:
        ans += 1
print(ans)

Submission status: Wrong Answer

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

ans = 0
endswith_a = 0
startswith_b = 0
for s in S:
    ans += s.count('AB')
    endswith_a += 1 if s.endswith('A') else 0
    startswith_b += 1 if s.startswith('B') else 0

if endswith_a == N:
    endswith_a -= 1
if startswith_b == N:
    startswith_b -= 1

ans += min(endswith_a, startswith_b)

print(ans)

Submission status: Wrong Answer

Solution code:
N=input()
LL=[]
def find(s):
    count=0
    for i in xrange(len(s)-1):
        if s[i]+s[i+1]=='AB':
            count+=1
    return count        

ans=0
start_B=0
end_A=0
same_time=0
for i in xrange(N):
    s=raw_input()
    ans+=find(s)
    if s[-1]=='A':
        end_A+=1
    if s[0]=='B':
        start_B+=1   
    if s[0]=='B' and s[-1]=='A':
        same_time+=1


#print(end_A,start_B,same_time,ans)
if end_A!=start_B:
    final=ans+min(end_A-same_time,start_B-same_time)
    if same_time>0:
        print(final+1)
    else:
        print(max(0,final)) 
else:
    final=ans+min(end_A-same_time,start_B-same_time)
    if same_time>0:
        print(final+(same_time)-1)
    else:
        print(final)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from string import ascii_uppercase
import sys, bisect, math
stdin = sys.stdin
read_int = lambda : list(map(int,stdin.readline().split()))
read_str = lambda : stdin.readline().rstrip()

N = read_int()[0]
S = [read_str() for _ in range(N)]

def solve():
    _a = 0
    b_ = 0
    ba = 0
    in_ab = 0

    # search
    for i in range(N):
        if S[i][0] == 'B' and S[i][-1:] == 'A':
            ba += 1
        elif S[i][0] == 'B':
            b_ += 1
        elif S[i][-1:] == 'A':
            _a += 1
        for j in range(len(S[i]) - 1):
            if S[i][j: j + 2] == 'AB':
                in_ab += 1

    ans = 0
    ans += in_ab + ba - 1 + max(0, min(_a - 1, b_ - 1))
    print(in_ab, ba, ans)
    if _a > 0: ans += 1
    if b_ > 0: ans += 1
    return ans

if __name__ == "__main__":
    print(solve())

Submission status: Wrong Answer

Solution code:
def countAB(S):
  ct=0
  flg = True
  pos=0
  while flg:
    idx = S.find('AB',pos)
    if idx!=-1:
      ct+=1
    else:
      flg = False
    pos = idx + 2
  return ct
 
N = int(input())
 
num_AB = 0
num_A = 0
num_B = 0
num_A_B = 0
for n in range(N):
  S = input()
  num_AB += countAB(S)
  if S[len(S)-1]=='A':
    num_A += 1
  if S[0]=='B':
    num_B += 1
  if S[len(S)-1]=='A' and S[0]=='B': 
    num_A_B += 1
    
num_AB_cmb = min(num_A,num_B)
if num_A == num_A_B and num_B == num_A_B:
  num_AB_cmb = num_A_B-1
 
print("{0}".format(num_AB + num_AB_cmb))

Submission status: Wrong Answer

Solution code:
from statistics import mean, median,variance,stdev
import numpy as np
import sys
import math
import fractions
import itertools
import copy
import collections
from operator import itemgetter
#以下てんぷら
def j(q):
    if q==1: print("Yes")
    elif q == 0:print("No")
    exit(0)


"""
def ct(x,y):
    if (x>y):print("+")
    elif (x<y): print("-")
    else: print("?")
"""

def ip():
    return int(input())
def printrow(a):
    for i in range(len(a)):
        print(a[i])
def combinations(n,r):
    if n<r:return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def permutations(n,r):
    if n<r:return 0
    return math.factorial(n) // math.factorial(n - r)
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)


#n = ip()                                     #入力整数1つ
#r,g,b,n= (int(i) for i in input().split())       #入力整数横2つ以上
#a = [int(i) for i in input().split()]        #入力整数配列
#a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列
n = ip()                      #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(n)]    #入力セット(整数改行あり)(2/2)
a=[input() for i in range(n)]    #入力セット(整数改行あり)(2/2)
#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
s = 0
righta = 0
leftb = 0
bothab = 0
for i in range(n):
    s+=a[i].count("AB")
    d = 0
    e = 0
    if a[i][len(a[i])-1] == 'A':
        d = 1
    if a[i][0] == 'B':
        e = 1
    if d and e:bothab+=1
    elif d: righta+=1
    elif e:leftb+=1
m = min(righta,leftb,bothab)
al = copy.copy(leftb)
ar = copy.copy(righta)
ab = copy.copy(bothab)
s+=m*2
righta-=m
leftb-=m
bothab-=m
if bothab==0:
    s+=min(righta,leftb)
elif righta ==0:
    s+=max(min(leftb,bothab),bothab+max(0,leftb)-1)
elif leftb==0:
    s+=max(min(righta,bothab),bothab+max(0,righta)-1)
altans = 0
if al and ar and ab:
    al-=1
    ar-=1
    altans = ab+1
    altans+=min(al,ar)
print(max(s,altans))

Submission status: Wrong Answer

Solution code:
import re
N = int(input())

S = []
for i in range(N):
  S.append(input())

inner = 0
Bxxx = 0
xxxA = 0
BxxA = 0

pattern = re.compile(r'AB')

for s in S:
  mo = pattern.findall(s)
  inner += len(mo)
  if s[0] == "B" and s[-1] == "A":
    BxxA += 1
  elif s[0] == "B":
    Bxxx += 1
  elif s[-1] == "A":
    xxxA += 1
total = inner + BxxA - 1
if xxxA > 0:
  total += 1
  xxxA -= 1
if Bxxx > 0:
  total += 1
  Bxxx -= 1
total += min(xxxA, Bxxx)
print(total)

Submission status: Wrong Answer

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

XA = 0
BX = 0
BXA = 0
cnt = 0
for Si in S:
    cnt += Si.count("AB")

    tp = (Si[0] == "B")*1 + (Si[-1] == "A")*2
    if tp == 1:
        BX += 1
    elif tp == 2:
        XA += 1
    elif tp == 3:
        BXA += 1

if BXA > 0:
    cnt += BXA - 1
    BXA = 1

pair = min(BX, XA)
if pair > 0:
    cnt += pair
    BX -= pair
    XA -= pair

if BXA > 0:
    if BX > 0:
        cnt += 1
    if XA > 0:
        cnt += 1

print(cnt)

Submission status: Wrong Answer

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

Axxx = [False]*n
xxxB = [False]*n
BxxA = [False]*n
cnt = 0
i = 0
for s in string_list:
    if s.endswith('A') and s.startswith('B'):
        BxxA[i] = True
    elif s.endswith('A'):
        Axxx[i] = True
    elif s.startswith('B'):
        xxxB[i] = True
    i += 1
    cnt += s.count('AB')
    
cnt += min(Axxx.count(True), xxxB.count(True))
nBxxA = BxxA.count(True)

if nBxxA > 1:
    cnt += nBxxA - 1
    
if Axxx.count(True) == xxxB.count(True):
    cnt += Axxx.count(True)
elif abs(Axxx.count(True) - xxxB.count(True)) > 0:
    if nBxxA > 0:
        cnt += 1
        
print(cnt)

Submission status: Wrong Answer

Solution code:
import re

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

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

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

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

Submission status: Wrong Answer

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

print(min(add,N-1) + ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s_b = 0
s_a = 0
s_ab = 0
s_a_b = 0
for i in range(n):
  s = input()
  s_ab += s.count("AB")
  if s[0] == "B":
    s_b += 1
  if s[-1] == "A":
    s_a += 1
    if s[0] == "B":
        s_a_b += 1
ans = s_ab+min(s_b,s_a)
if s_a_b == n:
  ans -= 1
print(ans)

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
        if top_B == 0 and both > 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
        if both > 0:
            if top_B == 0:
                top_B += 1
                both -= 1

    ans += min(top_B, tail_A)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
s = ['A']*N
cnt = 0
a_end = 0
b_start = 0
a_and_b = 0
for i in range(N):
    s[i] = input()
    cnt += s[i].count('AB')
    if s[i][-1] == 'A':
        a_end += 1
    if s[i][0] == 'B':
        b_start += 1
    if s[i][0] == 'B' and s[i][-1] == 'A':
        a_and_b += 1
if a_and_b % 2 == 1:
    print(cnt+min(a_end, b_start)-1)
else:
    print(cnt+min(a_end, b_start))

Submission status: Wrong Answer

Solution code:
n = int(input())
a = 0
b = 0
ab = 0
b_a = 0
for i in range(n):
    s = input()
    if s[0] == "B" and s[-1] == "A":
        b_a += 1
    elif s[0] == "B":
        b += 1
    elif s[-1] == "A":
        a += 1
    for j in range(len(s) - 1):
        if s[j] == "A" and s[j + 1] == "B":
            ab += 1
if a > b:
    a, b = b, a
ans = ab
if b_a <= b:
    ans += a + b_a
else:
    ans += a + b + min(b_a - b, b - a)
print(ans)

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
ans += max(ba - 1, 0)
ans += min(a, b)
if 0 < ba and a != b:
    ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = 0
r_a = 0
l_b = 0
for i in range(n):
    S = input()
    for j in range(len(S) - 1):
        if S[j] == 'A' and S[j + 1] == 'B':
            a += 1
    if S[-1] == 'A':
            r_a += 1
    if S[0] == 'B':
            l_b += 1
if r_a == l_b == n:
    print(a + r_a - 1)
else:
    print(a + min(r_a, l_b))

Submission status: Wrong Answer

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

c = 0
a = 0
b = 0
ab = 0

for i in range(0, n):
    for j in range(1, len(s[i])):
        if s[i][j-1:j+1] == "AB":
            c += 1
    if s[i][-1] == "A" and s[i][0] == "B":
        ab += 1
    elif s[i][0] == "B":
        b += 1
    elif s[i][-1] == "A":
        a += 1
        
s = c + ab - 1

if(a > 0):
    s += 1
    a -= 1
if(b > 0):
    s += 1
    b -= 1
s += min(a, b)
print(s)

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N = INT()
num_either = 0
num_A = 0
num_B = 0

count = 0
for _ in range(N):
	s = input()
	if s[-1] == "A" and s[0] == "B":
		num_either += 1
	elif s[-1] == "A":
		num_A += 1
	elif s[0] == "B":
		num_B += 1

	for i, char in enumerate(s):
		if i == len(s)-1:
			break
		if s[i] == "A" and s[i+1] == "B":
			count += 1
# print(count)
if num_either >= 2:
	count += num_either-1
	num_either = 1
# print(num_A, num_B, num_either)
if num_A > num_B:
	if num_either != 0:
		count += num_B+1
	else:
		count += num_B
elif num_B > num_A:
	if num_either != 0:
		count += num_A+1
	else:
		count += num_A
else:
	count += num_A
print(count)

Submission status: Wrong Answer

Solution code:
N=input()

ans=0
r_a_cnt=0
l_b_cnt=0
both=0

for _ in range(N):
	s=raw_input()
	if s[0]=="B": l_b_cnt+=1
	if s[-1]=="A": r_a_cnt+=1
	if s[0]=="B" and s[-1]=="A": both+=1

	len_s=len(s)
	for i in range(len_s-1):
		if s[i:i+2]=="AB":
			ans+=1

if l_b_cnt==r_a_cnt==both:
	ans+=min(l_b_cnt, r_a_cnt)-1
else:
	ans+=min(l_b_cnt, r_a_cnt)
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
for i in range(N):
    flag = False
    if a[i][0] == "B":
        if a[i][-1] == "A":
            yobiflag += 1
            bflag += 1
            aflag += 1
        else:
            bflag += 1
    else:
        if a[i][-1] == "A":
            aflag += 1

    for j in range(len(a[i])):

        if a[i][j] == "B" and flag:
            cnt += 1
        else:
            flag = False

        if a[i][j] == "A":
            flag = True

if yobiflag == N:
    aflag -= 1
# print(cnt)
# print(aflag)
# print(bflag)
print(cnt + min(aflag, bflag, ))