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

A = 0
B = 0
AB = 0
Ans = 0

for i in s:
  if i[0] == "B" and i[-1] == "A":
    AB += 1
  elif i[0] == "B":
    B += 1
  elif i[-1] == "A":
    A += 1
  f = False
  for j in i:
    if j == "B" and f:
      Ans += 1
    if j == "A":
      f = True
    else:
      f = False

if AB != 0:
  Ans += AB - 1
  if A != B:
    Ans += 1
Ans += min(A, B)

print(Ans)

Submission status: Wrong Answer

Solution code:
a = int(input())
s = 0
A=B=0
d = {"A":0,"B":0}
for i in range(a):
    t = input()
    s+=t.count("AB")
    if t[0]=="B":B+=1
    if t[-1]=="A":A+=1
print(s+min(A,B))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

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

ans = 0
fb = 0
la = 0
dottimo = 0
for s in ss:
    L = len(s)
    flag1 = flag2 = False
    for i in range(L-1):
        if s[i:i+2] == 'AB':
            ans += 1

    if s[0] == 'B':
        fb += 1
        flag1 = True

    if s[-1] == 'A':
        la += 1
        flag2 = True

    if flag1 and flag2:
        dottimo += 1

if fb == la and fb == dottimo:
    print(ans+dottimo-1)
else:
    print(ans+min(la,fb))

Submission status: Wrong Answer

Solution code:
N = int(input())

ab = 0 #naka
a = 0 #matsubi
b = 0 #sentou

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':
        a += 1
    if s[0] == 'B':
        b += 1
    ab += count(s)
    
print(ab + min(N-1,min(a,b)))

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
print(sum([c.count('AB')for c in s])+e)

Submission status: Wrong Answer

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


def solve(N: int, s: "List[str]"):
    count_AB = 0
    count_endswith_A = 0
    count_startswith_B = 0
    for ss in s:
        count_AB += ss.count('AB')
        if ss.endswith('A'):
            count_endswith_A += 1
        if ss.startswith('B'):
            count_startswith_B += 1
    print(count_AB + min(N-1, count_endswith_A, count_startswith_B))
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    s = [ next(tokens) for _ in range(N) ]  # type: "List[str]"
    solve(N, s)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[input() for _ in range(n)]
cnt_ab=0
cnt_a=0
cnt_b=0
for i in range(n):
    cnt_ab += s[i].count('AB')
    if s[i][-1] == 'A':
        cnt_a += 1
    if s[i][0] == 'B':
        cnt_b += 1
cnt_ab += min(cnt_a,cnt_b)
print(cnt_ab)

Submission status: Wrong Answer

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

    inner = 0
    for s in S:
        inner += s.count("AB")
    
    B_begin = 0
    for s in S:
        if s[0] == "B": B_begin += 1
    A_ended = 0
    for s in S:
        if s[-1] == "A" : A_ended += 1
    
    mm = min(A_ended, B_begin)
    
    print(inner + mm)
    

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

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

a = 0
c = 0
b = 0
for S in s:
    if S[0] == 'B':
        b += 1
    if S[-1] == 'A':
        a += 1
    l = len(S)
    for j in range(l-1):
        if S[j] == 'A' and S[j+1] == 'B':
            c += 1

print(c+min([a,b,N-1]))

Submission status: Wrong Answer

Solution code:
n,*s=open(0)
a=b=c=0
for t in s:
    a+=t[-2]=='A'
    b+=t[0]=='B'
    c+=t.count('AB')
print(min(a,b)+c)

Submission status: Wrong Answer

Solution code:

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

print(ans + min (acount,bcount))

Submission status: Wrong Answer

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

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

ans = cnt + min(cntA, cntB)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
#s = []
ans = 0
A = 0
B = 0
for i in range(N):
    si = input()
    for j in range(len(si)-1):
        if si[j] == 'A' and si[j+1] == 'B':
            ans += 1
    if si[0] == 'B':
        B += 1
    if si[len(si)-1] == 'A':
        A += 1
    #s.append(si)
print(ans+min(A,B))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
s_list = [input() for _ in range(N)]
end_a_num = 0
start_b_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

ans+= min(end_a_num,start_b_num)
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
Alist = [word for word in S if word[-1] == 'A']
Blist = [word for word in S if word[0] == 'B']
Slist = [word for word in S if 'AB' in word]
print(len(Slist)+min(len(Alist),len(Blist)))

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[]
ctr=0
ctr_a=0
ctr_b=0
for i in range(n):
    s.append(str(input()))
    if "AB" in s[i]:
        ctr+=1
    if s[i][-1]=="A":
        ctr_a+=1
    if s[i][0]=="B":
        ctr_b+=1
    
print(ctr+min(ctr_a,ctr_b))

Submission status: Wrong Answer

Solution code:
n = int(input())
sl = [input() for _ in range(n)]
sb,la,cnt = 0,0,0
for s in sl:
  cnt += s.count("AB")
  if s[0] == "B":
    sb += 1
  if s[-1] == "A":
    la += 1
print(cnt + min(la,sb))

Submission status: Wrong Answer

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

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==n:e-=1
print(sum([c.count('AB')for c in s])+e)

Submission status: Wrong Answer

Solution code:
N=int(input())
cnt=0
Bcnt=0
Acnt=0
for i in range(N):
    S=input()
    if S[-1]=="A":
        Acnt+=1
    if S[0]=="B":
        Bcnt+=1
    cnt+=S.count("AB")
if Acnt==Bcnt and Acnt==N:
    cnt+=N-1
else:
    cnt+=min(Acnt,Bcnt)
print(cnt)

Submission status: Wrong Answer

Solution code:
from sys import stdin
N = int(input())

middle = 0
countB = 0
countA = 0

for i in range(N):
    s = input()
    middle += s.count("AB")
    if s[0] == "B":
        countB +=1
    if s[-1] == "A":
        countA +=1

print(middle+min(countB, countA))

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
for i in range(n):
    s = input()
    if s.startswith("B"):
        enda += 1
    if s.endswith("A"):
        begb += 1
    for a, b in zip(s, s[1:]):
        if a == "A" and b == "B":
            ab += 1

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

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [list(input()) for i in range(n)]
a,b,c = 0,0,0
for i in range(n):
        for j in range(len(s[i])-1):
                if s[i][j] =="A" and s[i][j+1] == "B":
                        c += 1
                else:
                        continue
        if s[i][0] == "B":
                b += 1
        if s[i][-1] == "A":
                a += 1

if a > b:
        d = b
else:
        d = a

if n - 1 < d:
        d = n -1

print(d + c)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque, OrderedDict
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from math import ceil, floor
from sys import setrecursionlimit

import heapq as hq
import itertools as its
import operator as op


# globals
inf = float('inf')
N = 0


def set_inputs():
    global N
    return


def main():
    setrecursionlimit(100000)
    set_inputs()
    # ----------MAIN----------
    n = get_int()
    s = get_data(n, [str])
    ans = 0
    a = 0
    b = 0
    for si in s:
        if si[-1] == 'A':
            a += 1
        if si[0] == 'B':
            b += 1
        for c1, c2 in zip(si, si[1:]):
            if c1 == 'A' and c2 == 'B':
                ans += 1
    ans += min(a, b)
    print(ans)
    return


def get_int():
    return int(input())


def get_float():
    return float(input())


def get_str():
    return input().strip()


def get_li():
    return [int(i) for i in input().split()]


def get_lf():
    return [float(f) for f in input().split()]


def get_lc():
    return list(input().strip())


def get_data(n, types, sep=None):
    if len(types) == 1:
        return [types[0](input().strip()) for _ in range(n)]
    return list(zip(*(
        [t(x) for t, x in zip(types, input().strip().split(sep=sep))]
        for _ in range(n)
    )))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())

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

print(ans + min(cnt_a, cnt_b))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

result = 0
A = 0
B = 0
for i in range(N):
    s.append(input())

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

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

print(result + onon)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
ans = 0
numa = 0
numb = 0
for _ in range(N):
    s = input()
    num = 0
    for x,y in zip(s, s[1:]):
        if x == 'A' and y == 'B' :
            num += 1
    ans += num
    if s[0] == 'B':
        numb += 1
    if s[-1] == 'A':
        numa += 1
print(ans + min(numa, numb))

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 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 I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)


def main():
    n = I()
    if n == 1:
        s = S()
        l = s.split("AB")
        return len(l) - 1

    a = [S() for _ in range(n)]
    c = collections.defaultdict(int)
    d = collections.defaultdict(int)
    ab = 0
    e = 0
    for s in a:
        c[s[0]] += 1
        d[s[-1]] += 1
        if s[0] == 'B' and s[-1] == 'A':
            ab += 1
        l = s.split("AB")
        e += len(l) - 1
    t = min([c['B'], d['A'],ab-1])

    return e + t


print(main())

Submission status: Wrong Answer

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

AB = 0
lastA = 0
firstB = 0
for s in S:
  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

print(AB + min(N-1, lastA, firstB))

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 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 I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)


def main():
    n = I()
    if n == 1:
        s = S()
        l = s.split("AB")
        return len(l) - 1

    a = [S() for _ in range(n)]
    c = collections.defaultdict(int)
    d = collections.defaultdict(int)
    e = 0
    for s in a:
        c[s[0]] += 1
        d[s[-1]] += 1
        l = s.split("AB")
        e += len(l) - 1
    t = min([c['B'], d['A'],n-1])

    return e + t


print(main())

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 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 I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)


def main():
    n = I()
    a = [S() for _ in range(n)]
    c = collections.defaultdict(int)
    d = collections.defaultdict(int)
    e = 0
    for s in a:
        c[s[0]] += 1
        d[s[-1]] += 1
        l = s.split("AB")
        e += len(l) - 1
    t = min([c['B'], d['A'],n-1])

    return e + t


print(main())

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

a_cnt = 0
b_cnt = 0

cnt = 0

for _ in range(N):
  s = input()
  pos = 0
  
  while(True):
    pos = s[pos:].find('AB')
    if pos == -1:
      break
    pos += 2
    cnt += 1
    
  if s[0] == 'B':
    b_cnt += 1
  if s[-1] == 'A':
    a_cnt += 1
    
print(cnt + min(a_cnt, b_cnt))

Submission status: Time Limit Exceeded

Solution code:
# div2019C - AB Substrings
from itertools import permutations


def main():
    N = int(input())
    S = tuple(input().rstrip() for _ in range(N))
    ans = 0
    for perm in permutations(S, N):
        x = "".join(perm)
        ans = max(ans, x.count("AB"))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import itertools
n = int(input())
s =[]
li =[]
al = []
ans = []
for _ in range(n):
    a = input()
    s.append(a)
for i in range(1,n+1):
    b = list(itertools.permutations(s,i))
    li.append(b)
for j in range(len(li)):
    c = ""
    for k in range(len(li[j])):
        c = ''.join(li[j][k])
        al.append(c)
for l in range(len(al)):
    d = al[l].count("AB")
    ans.append(d)
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

N = int(input())

inputs = []
end = []
start = []
pair = []

Max = 0
B_count = 0
A_count = 0

for i in range(0,N):
    tex = input()
    inputs.append(tex)
    head = tex[0] 
    tail = tex[-1]
    if head == 'B' or tail == 'A':
        end.append(tail)
        start.append(head)
        pair.append(tex[0]+tex[len(tex) - 1])
    Max += tex.count('AB')

count = 0
perm = permutations(pair)
for p in perm:
    tex = ''.join(p)
    c = tex.count('AB')
    if count < c:
        count = c
print(count+Max)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

N = int(input())
inputs = []
max = 0

for i in range(0,N):
    inputs.append(input())

perm = permutations(inputs,N)

for p in perm:
    text = ''.join(p)
    c = text.count('AB')
    if c > max:
        max = c

print(max)

Submission status: Time Limit Exceeded

Solution code:
import sys,random
try: sys.stdin = open('in.in','r')
except: pass

ans = 0
allboth = 1
l = r = 0

n = int(input())
for i in range(n):
	s = input().strip()
	ans += s.count('AB')
	if s[0] == 'B' or s[-1] == 'A':
		l += s[0] == 'B'
		r += s[-1] == 'A'
		if s[0] != 'B' or s[-1] != 'A':
			allboth = 0

ans += min(l,r)
if allboth and ans:
	while True:
		pass
	ans -= 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
headB=0
tailA=0 
both = 0
ans = 0
for j in range(N):
    t = input()
    if t[0] == "B":
        if t[-1] == "A":
            both += 1
        else:
            headB += 1
    elif t[-1] == "A":
        tailA += 1
    ans += t.count("AB")
while both > 0:
    tmp = min(tailA,both)
    ans += tmp
    both -= tmp
    tmp = min(headB,both)
    ans += tmp
    both -= tmp
ans += min(headB,tailA)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
import itertools
clist = []
for i in range(n):
    clist.append(str(input()))
cnt_list = []
for i in itertools.permutations(clist):
    #print( "".join((list(i))))
    cnt_list.append( "".join((list(i))).count("AB") )
print(max(cnt_list))

Submission status: Time Limit Exceeded

Solution code:
import itertools

N=int(input())
s=list(input() for _ in range(N))
L=list(itertools.permutations(s))
c=0
for i in L:
    if c<''.join(i).count('AB'):
        c=''.join(i).count('AB')
print(c)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n = int(input())
ans = 0
string_list = [input() for i in range(n)]
count_AB = 0
ab_list = []
for i in range(n):
    if(string_list[i].startswith('B') or string_list[i].endswith('A')):
        ab_list.append(string_list[i])
    elif('AB' in string_list[i]):
        count_AB += string_list[i].count('AB')

for v in itertools.permutations(ab_list):
    s = ''.join(v)
    ans = max(ans, s.count('AB'))
print(ans + count_AB)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import re

N = int(input())
string_list = [input() for i in range(N)]
count = 0
test = []
for v in itertools.permutations(string_list):
    test.append(len(re.findall('AB', ''.join(v))))
print(max(test))

Submission status: Time Limit Exceeded

Solution code:
import itertools

print(max([random_string.count('AB') for random_string in [''.join(pmt) for pmt in itertools.permutations((input() for i in range(int(input()))))]]))

Submission status: Time Limit Exceeded

Solution code:
import itertools
N = int(input())
s = [input().split() for _ in range(N)]
pattern = list(itertools.permutations(s))
result = 0
 
for i in range(len(pattern)):
    ls = list(pattern[i])
    string = ''.join([j for i in ls for j in i])
    tmp = string.count('AB')
    if result < tmp:
        result = tmp
 
print(result)

Submission status: Time Limit Exceeded

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

cnt_base = 0

for i in range(N):
    base = list(s[i])
    for j in range(len(base) - 1):
        if base[j] == "A" and base[j + 1] == "B":
            cnt_base += 1

pop_index = []

for i in range(N):
    base = list(s[i])
    if base[len(base) - 1] != "A" and base[0] != "B":
        pop_index.append(i)

def minus(num):
    return num - 1

while pop_index:
    s.pop(pop_index[0])
    pop_index.pop(0)
    pop_index = list(map(minus, pop_index))
    

cnt_ab = 0
cnt_a = 0
cnt_b = 0
for i in range(len(s)):
    base = list(s[i])
    if base[len(base) - 1] == "A" and base[0] == "B":
        cnt_ab += 1
    elif base[len(base) - 1] == "A":
        cnt_a += 1
    elif base[0] == "B":
        cnt_b += 1

result = cnt_base
while cnt_ab != 0 or cnt_a != 0 or cnt_b != 0:
    if cnt_a > 0:
        if cnt_ab > 0:
            result += cnt_ab
            if cnt_b > 0:
                result += 1
                cnt_b -= 1
            cnt_ab = 0
            cnt_a -= 1
        elif cnt_b > 0:
            result += 1
            cnt_a -= 1
            cnt_b -= 1
    elif cnt_ab > 0:
        result += cnt_ab - 1
        cnt_ab = 0

print(result)

Submission status: Time Limit Exceeded

Solution code:
import random
import itertools

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

lst = []
for i in itertools.permutations(s, N):
    rs = "".join(random.sample(s, N))
    if "AB" in rs:
        lst.append(rs.count("AB"))

print(max(lst))

Submission status: Time Limit Exceeded

Solution code:
import itertools
N = int(input())
s = [input().split() for _ in range(N)]
pattern = list(itertools.permutations(s))
result = 0

for i in range(len(pattern)):
    ls = list(pattern[i])
    string = ''.join([j for i in ls for j in i])
    tmp = string.count('AB')
    if result < tmp:
        result = tmp

print(result)

Submission status: Time Limit Exceeded

Solution code:
import itertools
n = int(input())
s_list = [input() for _ in range(n)]
res_list = []
for s in itertools.permutations(s_list):
    res_list.append(''.join(s).count('AB'))
print(max(res_list))

Submission status: Time Limit Exceeded

Solution code:
import itertools

n = int(input())
ans = 0
string_list = [input() for i in range(n)]
ab_list = []
for i in range(n):
    if('A' in string_list[i] or 'B' in string_list[i]):
        ab_list.append(string_list[i])

for v in itertools.permutations(ab_list):
    s = ''.join(v)
    ans = max(ans, s.count('AB'))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n = int(input())

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

c = itertools.permutations(s)
maxAB = 0

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

print(maxAB)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

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

        if s[0] == 'B' or s[-1] == 'A':
            if s[0] == 'B':
                first_b += 1
            if s[-1] == 'A':
                last_a += 1
            q.append(s)

    while first_b * last_a != 0 and len(q) > 1:
        q_ = deque()
        s = q.popleft()
        while len(q) > 0:
            s1 = q.popleft()

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

        q_.append(s)
        q = q_

    return ans


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

Submission status: Time Limit Exceeded

Solution code:
import itertools
n = int(input())
count = 0
l = []
for i in range(n):
  s = input()
  if "AB" in s or s[0] == "B" or s[-1] == "A":
    l.append(s)
ll = list(itertools.permutations(l))
for i in range(len(ll)):
  if "".join(ll[i]).count("AB") > count:
    count = "".join(ll[i]).count("AB")
print(count)

Submission status: Time Limit Exceeded

Solution code:
import itertools
n = int(input())
clist = []
for i in range(n):
       clist.append(str(input()))
cnt_list = []
for i in itertools.permutations(clist):
        cnt_list.append( "".join((list(i))).count("AB") )
print(max(cnt_list))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

N = int(input())
S = [input() for _ in range(N)]
# S = ["ABCA", "XBAZ", "BAD"]
# S = ["BEWPVCRWH", "ZZNQYIJX", "BAVREA", "PA", "HJMYITEOX", "BCJHMRMNK", "BP", "QVFABZ", "PRGKSPUNA"]
# S = ["RABYBBE","JOZ","BMHQUVA","BPA","ISU","MCMABAOBHZ","SZMEHMA"]


def calc_maximum_AB_sub_string(S):
    jointed = map(lambda x: "".join(x), permutations(S))
    counts = map(lambda x: x.count("AB"), jointed)
    return max(counts)


if __name__ == "__main__":
    print(calc_maximum_AB_sub_string(S))

Submission status: Time Limit Exceeded

Solution code:
N =  int(input())
S = [input() for _ in range(N)]
S = [s for s in S if "AB" in s or s[0] == "B" or s[-1] == "A"]
n = len(S)

import itertools
perm = itertools.permutations
ans = 0
for per in perm(S, n):
  x = "".join(per)
  ans = max(ans, x.count("AB"))
print(ans)

Submission status: Time Limit Exceeded

Solution code:


N = int(input())

x = []

for i in range(0, N):
	x.append(input())

summ = 0

import itertools

y = list(itertools.permutations(x))

for s in y:
	ss = list(s)
	n = ''.join(ss).count('AB')
	summ = summ if n < summ else n

print(summ)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n = int(input())
ans = 0
string_list = [input() for i in range(n)]
for v in itertools.permutations(string_list):
    s = ''.join(v)
    ans = max(ans, s.count('AB'))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
n = int(input())
clist = []
for i in range(n):
    clist.append(str(input()))
cnt_list = []
for i in itertools.permutations(clist):
    #print( "".join((list(i))))
    cnt_list.append( "".join((list(i))).count("AB") )

print(max(cnt_list))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

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

count_ab = 0
for s in sub_strs:
    count_ab += s.count('AB')
    
#print(count_ab)
    
top_back_s = [s[0]+s[-1] for s in sub_strs if s[0] == 'B' or s[-1] == 'A']

#print(top_back_s)
import itertools
ans = 0
for sub_str in itertools.permutations(top_back_s):
    join_s = ''.join(sub_str)
    ans = max(ans, join_s.count('AB'))
    
ans += count_ab
print(ans)

Submission status: Time Limit Exceeded

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

from itertools import permutations as perm

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

Submission status: Time Limit Exceeded

Solution code:
import itertools
n = int(input())
count = 0
l = []
for i in range(n):
  l.append(input())
ll = list(itertools.permutations(l))
for i in range(len(ll)):
  if "".join(ll[i]).count("AB") > count:
    count = "".join(ll[i]).count("AB")
print(count)

Submission status: Time Limit Exceeded

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
            else:
                q_.append(s1)

        q_.append(s)
        q = q_

    return ans


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

Submission status: Time Limit Exceeded

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


for i in itertools.permutations(A,N):
    B="".join(i)

    Y=B.count("AB")

    if X<Y:
        X=Y



print(X)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = 0
B = 0
BA = 0
num = 0
for i in range(N):
    k = input()
    if k[0] == 'B' and k[-1] == 'A':
        BA += 1
    elif k[0] == 'B':
        B += 1
    elif k[-1] == 'A':
        A += 1

    for j in range(N - 1):
        if k[j:j + 2] == 'AB':
            num += 1

num += max(0, BA - 1)
BA -= max(0, BA - 1)
num += min(BA, A) + min(BA, B)
A -= min(BA, A)
B -= min(BA, B)
num += min(A, B)
print(num)

Submission status: Accepted

Solution code:
import sys
def I(): return int(sys.stdin.readline().rstrip())
def S(): return sys.stdin.readline().rstrip()


N = I()

ans = 0
b_start,a_end,b_start_a_end = 0,0,0
# Bで始まりAで終わらない文字列、Bで始まらずAで終わる文字列、Bで始まりAで終わる文字列の個数
for i in range(N):
    s = S()
    if s[0] == 'B' and s[-1] == 'A':
        b_start_a_end += 1
    elif s[0] == 'B':
        b_start += 1
    elif s[-1] == 'A':
        a_end += 1
    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            ans += 1

if b_start_a_end == 0:
    print(ans+min(b_start,a_end))
else:
    ans += b_start_a_end-1  # b_start_a_end == 1 として良い
    if a_end > 0:
        ans += 1
        a_end -= 1
    if b_start > 0:
        ans += 1
        b_start -= 1
    ans += min(b_start,a_end)
    print(ans)