Problem:


Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6



Sample input:
ABCABC


Sample output:
3

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
AtCoder B
"""

# N = int(input())
# A = list(map(int,input().split())) # N row 1 column
# A = [int(input()) for _ in range(N)] # 1 row N column

# S = str(input()) # str(input()) == input() -> 'abc'
# S = list(input()) # abc -> ['a','b','c']

def main():
    S = list(input()) # abc -> ['a','b','c']
    out=0
    a=0
    b=False
    while S:
    for i in S:
        # print(S,a,out)
        s=i

        if s=="A":
            a+=1
            b=False
        elif s=="B":
            if b:
                b=False
                a=0
            else:
                b=True
        else:
            if b:
                out+=a
            else:
                a=0
            # a=0
            b=False
                

        # if S[0]=="A":
        #     a+=1
        #     del S[0]
        # elif S[0:2]==["B","C"]:
        #     del S[0:2]
        #     out+=a

        #     for _ in range(a):
        #         S.insert(0, "A")
        #     a=0
        # else:
        #     del S[0]
        #     a=0
    print(out)
    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from sys import stdin
import numpy as np
# import math
# import random
# import fractions
# import sys
# sys.setrecursionlimit(100000)
# N = int(stdin.readline().rstrip().split()[0])
# A = [int(x) for x in stdin.readline().rstrip().split()]
# N, X = [int(x) for x in stdin.readline().rstrip().split()]
# S = stdin.readline().rstrip().split()[0]
S = stdin.readline().rstrip().split()[0]
N = len(S)
newS=[]
i=0
while i<N:
  if i>N-2:
    newS.append(S[i])
    i+=1
  elif S[i:i+2]=="BC":
    newS.append("E")
    i+=2
  elif i>N-3:
    newS.append(S[i])
    i+=1
  elif S[i:i+3]=="ABC":
    newS.append("D")
    i+=3
  
  else:
    newS.append(S[i])
    i+=1
# print(newS)

lns = len(newS)
ans = 0
l = []
for i in range(lns-1):
  
  if newS[i]=="A" and newS[i+1]=="D":
    newS[i]="D"
    newS[i+1]="A"
    ans+=1
    if i<lns-3:
      if newS[i+2]=="D" and newS[i+3]=="E":
        newS[i+1]="D"
        l.append(i+3)
        newS[i+3]="Z"
for i in l:
  del newS[i]
lns = len(newS)
for i in range(lns-1):
  if newS[lns-1-i]=="E" and newS[lns-2-i]=="D":
    newS[lns-1-i]="D"
    newS[lns-2-i]="E"
    ans+=1
# print(ans,newS)

newS.append("Z")
Dcount = 0
Acount = 0


for i in range(lns+1):
  if newS[i]=="D":
    Dcount+=1
  else:
    if Dcount!=0:
      ans+=(Dcount*(Dcount+1))//2
      # Dcountはまだ初期化しない
    """
      ans+=Acount
      Acount=0
    if newS[i]=="A":
      Acount+=1
      Dcount=0
    elif newS[i]=="E":
      if Dcount!=0:
        ans+=1
      Acount=0
    """
    Dcount=0
print(ans)

Submission status: Runtime Error

Solution code:
s = input()
cnt = 0
while True:
    t = re.subn('ABC', 'BCA', s)
    if t != 0:
        cnt += t[1]
    else:
        break
print(cnt)

Submission status: Runtime Error

Solution code:
s=input()
s=list(s)
s.append('D')
s.append('D')
n=[]
i=0
ct=0
aa=[i for i, x in enumerate(s) if x == 'A']
ct+=len(aa)
if len(aa)>0:
    for i in range(len(aa)):
        while True:
            if s[aa[i]+3]=='B' and s[aa[i]+4]=='C':
                ct+=1
                n.append(aa[i])
                aa[i]+=4
            if aa[i]==len(s)-2:break
            else:break
        if aa[i]>=1:
            while True:
                if s[aa[i]-1]=='A':
                    ct+=1
                    aa[i]-=1
                if aa[i]>=3 and s[aa[i]-1]=='C':
                    if aa[i]-3 in aa:
                        ct+=1
                        break
                    else:break
                if aa[i]-1==0:
                    if s[0]=='A':
                        ct+=1
                    break
print(ct)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
qS = input()


def replace(s, count):
    fi = s.find('ABC')
    if fi >= 0:
        newS = 'A' + s[fi+3:]
        return replace(newS, count + 1)
    else:
        return count


print(replace(qS, 0))

Submission status: Runtime Error

Solution code:
from sys import stdin
import numpy as np
# import math
# import random
# import fractions
# import sys
# sys.setrecursionlimit(100000)
# N = int(stdin.readline().rstrip().split()[0])
# A = [int(x) for x in stdin.readline().rstrip().split()]
# N, X = [int(x) for x in stdin.readline().rstrip().split()]
# S = stdin.readline().rstrip().split()[0]
S = stdin.readline().rstrip().split()[0]
N = len(S)
newS=[]
i=0
while i<N:
  if i>N-2:
    newS.append(S[i])
    i+=1
  elif S[i:i+2]=="BC":
    newS.append("E")
    i+=2
  elif i>N-3:
    newS.append(S[i])
    i+=1
  elif S[i:i+3]=="ABC":
    newS.append("D")
    i+=3
  
  else:
    newS.append(S[i])
    i+=1
print(newS)

lns = len(newS)
ans = 0
for i in range(lns-1):
  
  if newS[i]=="A" and newS[i+1]=="D":
    newS[i]="D"
    newS[i+1]="A"
    ans+=1
    if i<lns-4:
      if newS[i+3]=="E":
        newS[i]="D"
        del newS[i+3]
        
lsn = len(newS)
for i in range(lns-1):
  if newS[lns-1-i]=="E" and newS[lns-2-i]=="D":
    newS[lns-1-i]="D"
    newS[lns-2-i]="E"
    ans+=1
print(ans,newS)

newS.append("Z")
Dcount = 0
Acount = 0


for i in range(lns+1):
  if newS[i]=="D":
    Dcount+=1
  else:
    if Dcount!=0:
      ans+=(Dcount*(Dcount+1))//2
      # Dcountはまだ初期化しない
    """
      ans+=Acount
      Acount=0
    if newS[i]=="A":
      Acount+=1
      Dcount=0
    elif newS[i]=="E":
      if Dcount!=0:
        ans+=1
      Acount=0
    """
    Dcount=0
print(ans)

Submission status: Runtime Error

Solution code:
#!venv/bin/python
 
import math
import numpy as np
import random
import copy
import statistics 
import bisect
import heapq
from collections import defaultdict 
import time

#N, A, B, C, D = [ int(x) for x in input().split() ]

S = input()

ans = 0

pointer = 0
while True:
    abc_p = S[pointer:].find("ABC")
    if abc_p == -1:
        break
    abc_p = pointer + abc_p
    left_a_num = 0
    _s = S[abc_p:pointer - 1:-1] if pointer >= 1 else S[abc_p::-1]
    for s in _s:
        if s == 'A':
            left_a_num += 1
        else:
            break
    left_a_num -= 1
    pointer = abc_p + 3
    ABC_cnt = 1
    BC_cnt = 0
    BC_incr = 0
    A_cnt = 0
    while True:
        if pointer + 3 <= len(S) and S[pointer:pointer + 3] == 'ABC':
            ABC_cnt += 1
            pointer += 3
            if A_cnt:
                ans += A_cnt
                ans += BC_incr
        elif pointer + 2 <= len(S) and S[pointer:pointer + 2] == 'BC':
            BC_cnt += 1
            BC_incr += ABC_cnt
            pointer += 2
        elif pointer + 1 <= len(S) and S[pointer + 1] == 'A':
            A_cnt += 1
            pointer += 1
        else:
            break
    ans += BC_incr
    _n = min(BC_cnt,left_a_num)
    ans += int((_n * (_n + 1)) / 2)
    ABC_cnt += _n
    ans += int((ABC_cnt * (ABC_cnt + 1)) / 2)

print(ans)

Submission status: Runtime Error

Solution code:
s=input()
s=list(s)
s.append('D')
s.append('D')
n=[]
i=0
ct=0
aa=[i for i, x in enumerate(s) if x == 'A']
ct+=len(aa)
for i in range(len(aa)):
    while True:
        if s[aa[i]+3]=='B' and s[aa[i]+4]=='C':
            ct+=1
            n.append(aa[i])
            aa[i]+=4
        if aa[i]==len(s)-2:break
        else:break
    if aa[i]>=1:
        while True:
            if s[aa[i]-1]=='A':
                ct+=1
                aa[i]-=1
            if aa[i]>=3 and s[aa[i]-1]=='C':
                if aa[i]-3 in aa:
                    ct+=1
                    break
                else:break
            if aa[i]-1==0:
                if s[0]=='A':
                    ct+=1
                break
print(ct)

Submission status: Runtime Error

Solution code:
import sys

def check(abc_lst, idx, cnt):
    if abc_lst[idx:idx+3] == [1,2,3]:
        cnt += 1
        abc_lst[idx] = 2
        abc_lst[idx+1] = 3
        abc_lst[idx+2] = 1
        if idx > 0 and abc_lst[idx-1] == 1:
            cnt = check(abc_lst, idx-1, cnt)
    while idx < len(abc_lst) - 2:
        if abc_lst[idx+1:idx+4] == [1,2,3]
            cnt = check(abc_lst, idx+1, cnt)
        idx += 1
    return cnt

sys.setrecursionlimit(10**9)

S = input()
ABC_dict = {'A':1, 'B':2, 'C':3}
abc_lst = [ABC_dict[S[i]] for i in range(len(S))]
print(check(abc_lst, 0, 0))

Submission status: Runtime Error

Solution code:
import re
S = input()
N1 = S.replace('A','0').replace('BC','1')
S_li = re.split('[BC]')

count = 0
for l in S_li:
    if len(l):
        while True:
            a = l.find('0')
            if a<0:
                break
            bc = l.rfind('1')
            if a < bc:
                l = l[a+1:bc]
                count += (bc-a)
            else:
                break

print(str(count))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
qS = input()


def replace(s, count):
    fi = s.find('ABC')
    if fi >= 0:
        newS = s[:fi] + 'BCA' + s[fi+3:]
        return replace(newS, count + 1)
    else:
        return count


print(replace(qS, 0))

Submission status: Runtime Error

Solution code:
S = input()

flag = 0
ans = 0
i = 0
S= list(S)


while flag == 0:
    if len(S) < 3+i:
        flag = 1
     elif S[i]=="A" and S[i+1]=="B" and S[i+2]=="C":
        S[i] = 'B'
        S[i+1] = 'C'
        S[i+2] = 'A'
        i=0
        ans+=1
    elif S[i]=="A":
        i+=1
    else:
        S.pop(i)
print(ans)

Submission status: Runtime Error

Solution code:
s = str(input())

s = s.replace('BC', 'D').replace('B', 'C').replace('AC', 'C').split('C')
sl = [x for x in sl if x]

c = 0
for l in sl:
    l = list(l)
    ind = [i for i, x in enumerate(l) if x == 'D']
    for i in ind:
        c += l[:i].count('A')
        
print(c)

Submission status: Runtime Error

Solution code:
import sys

def main():
    input = sys.stdin.readline
    S = list(input().strip())
    n = len(S)

    ans = 0
    cnt = 0
    for i in range(n):
        if S[i:i+3] == ['A', 'B', 'C']:
            cnt += 1
            S[i] = 'B'
            S[i+1] = 'C'
            S[i+2] = 'A'

    S = S[::-1]
    for i in range(n):
        if S[i:i+3] == ['C', 'B', 'A']:
            cnt += 1
            S[i] = 'A'
            S[i+1] = 'C'
            S[i+2] = 'B'

    ans += cnt
    while cnt > 0:
        cnt = 0
        S = S[::-1]
        for i in range(n):
        if S[i:i+3] == ['A', 'B', 'C']:
            cnt += 1
            S[i] = 'B'
            S[i+1] = 'C'
            S[i+2] = 'A'

        S = S[::-1]
        for i in range(n):
            if S[i:i+3] == ['C', 'B', 'A']:
                cnt += 1
                S[i] = 'A'
                S[i+1] = 'C'
                S[i+2] = 'B'

        ans += cnt


    return ans


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

Submission status: Runtime Error

Solution code:
# coding: UTF-8
# sample code

import re

s = input()

num = 0
i = 0
t = [ s ]
while l = len(re.findall('ABC', t[i])) != 0:
	num += l
	u = t[i].replace('ABC', 'BCA')
	t.append(u)
	i += 1

print(num)

Submission status: Runtime Error

Solution code:
s = input()
ss = [ si for si in s ]

cnt = 0
cnti = 0
cntj = 0
i = 0
while True:
    while True:
        if s[i] != "A":
            i += 3
        elif i < len(s)-2 and ss[i] == "A" and ss[i+1] == "B" and ss[i+2] == "C":
            ss[i], ss[i+1], ss[i+2] = "B", "C", "A"
            cnt += 1
            i += 1
            cnti = 0
            if i < len(s)-2-cntj:
                break
        elif i >= len(s)-2-cntj:
            cnti += 1
            cntj += 1
            i = cntj*2
            break
        i += 1
    if cnti > 2:
        break
print(cnt)

Submission status: Runtime Error

Solution code:
import math

s = input()
if len(s) < 3:
    print(0)
    exit(0)
l = []
for i in range(2):
    l.append(s[len(s) // 3 * i:len(s) // 3 * (i + 1)])
l.append(s[len(s) // 3 * 2:])
ans = 0
for i, s in enumerate(l):
    for i in reversed(range(int(math.log2(len(s)))+1)):
        w = 2**i
        while "A" + "BC" * w in l[i] or "A" * w + "BC" in l[i]:
            m = l[i].count("A" + "BC" * w)
            l[i] = l[i].replace("A" + "BC" * w, "BC" * w + "A")
            m += l[i].count("A" * w + "BC")
            l[i] = l[i].replace("A" * w + "BC", "BC" + "A" * w)
            ans += w * m
s = ''.join(l)
for i in reversed(range(int(math.log2(len(s)))+1)):
    w = 2**i
    while "A" + "BC" * w in s or "A" * w + "BC" in s:
        m = s.count("A" + "BC" * w)
        s = s.replace("A" + "BC" * w, "BC" * w + "A")
        m += s.count("A" * w + "BC")
        s = s.replace("A" * w + "BC", "BC" + "A" * w)
        ans += w * m
print(ans)

Submission status: Runtime Error

Solution code:
s = list(input())
n = len(s)
s = s+['z','z']
mem = []
c = 0
run = 0
i=0
while(i<n):
    if s[i]=='A' and s[i+1]=='B' and s[i+2]=='C':
        c+=1
        s[i] = 'B'
        s[i + 1] = 'C'
        s[i + 2] = 'A'
        mem.append(i+2)
        run=1
        i+=3
    else:
        i+=1
        if s[i]=='A':
            mem.append(i)
while(run):
    run = 0
    for i in range(len(mem)):
        idex = mem[i]
        if s[idex] == 'A' and s[idex + 1] == 'B' and s[idex + 2] == 'C':
            c += 1
            s[idex] = 'B'
            s[idex + 1] = 'C'
            s[idex + 2] = 'A'
            mem.append(i + 2)
            run = 1
            mem[i]= idex+2
print(c)

Submission status: Runtime Error

Solution code:
def inverse(a):
    return pow(a, mod - 2, mod)

def main():
    n,a,b,c,d = map(int, input().split())
    a -=1
    b -=1
    c -=1
    d -=1

    s = input()

    a_r = a
    cnt = 0
    for i in range(a, n):
        if s[i] == '#':
            cnt += 1
        else:
            cnt = 0
        a_r = i
        if cnt == 2:
            a_r = i
            break

    b_r = b
    cnt = 0
    for i in range(b, n):
        if s[i] == '#':
            cnt += 1
        else:
            cnt = 0
        b_r = i
        if cnt == 2:
            b_r = i
            break
    if a_r < c or b_r < d:
        print('No')
        return
    if c < d:
        print('Yes')
        return
    cnt = 0
    for i in range(b, d):
        if s[i] == '.':
            cnt += 1
        else:
            cnt = 0
        if cnt > 2:
            print('Yes')
            return

    if s[b-1] == '.' and s[b+1] == '.':
        print('Yes')
        return
    if s[d-1] == '.' and s[d+1] == '.':
        print('Yes')
        return
    import random
    if random.randint(0, 5) == 1:
        print('Yes')
        return
    print('No')


main()

Submission status: Runtime Error

Solution code:
import sys

def check(abc_lst, idx, cnt):
    if abc_lst[idx:idx+3] == [1,2,3]:
        cnt += 1
        abc_lst[idx] = 2
        abc_lst[idx+1] = 3
        abc_lst[idx+2] = 1
        if idx > 0 and abc_lst[idx-1] == 1:
            cnt = check(abc_lst, idx-1, cnt)
    if idx < len(abc_lst) - 2:
        cnt = check(abc_lst, idx+1, cnt)
    return cnt

sys.setrecursionlimit(10**9)

S = input()
ABC_dict = {'A':1, 'B':2, 'C':3}
cnt = 0
abc_lst = [ABC_dict[S[i]] for i in range(len(S))]
for i in range(len(S)-2):
    abc = abc_lst[i:i+3]
    if abc == [1,2,3]:
        cnt += 1
        abc_lst[i] = 2
        abc_lst[i+1] = 3
        abc_lst[i+2] = 1
        if i > 0 and abc_lst[i-1] == 1:
            cnt = check(abc_lst, i-1, cnt)

for i in range(len(S)-2)[::-1]:
    abc = abc_lst[i:i+3]
    if abc == [1,2,3]:
        cnt += 1
        abc_lst[i] = 2
        abc_lst[i+1] = 3
        abc_lst[i+2] = 1
        if i + 2 < len(S) and abc_lst[i+1] == 2 and abc_lst[i+2] == 3:
            cnt = check(abc_lst, i-1, cnt)

print(cnt)

Submission status: Runtime Error

Solution code:
S=list(input())

def repABC(S,ans,A_position):
    S1=S[:]
    S2 =S[:]
    S2.pop(0)
    S3 =S2[:]
    S3.pop(0)
    
    
    for i in A_position:
        if S1[i]=="A" and S2[i]=="B" and S3[i]=="C":
            S[i]="B"
            S[i+1]="C"
            S[i+2]="A"
            ans=ans+1
            
    return S,ans

ans=0
for i in range(10000000000):
    if len(S)<2:
        break
        
    flag=ans
    A_position=[i for i, x in enumerate(S) if x == "A" and i <len(S)-1]
    S,ans=repABC(S,ans,A_position)
    if flag==ans:
        break
        
print(ans)

Submission status: Runtime Error

Solution code:
S=list(input())

def repABC(S,ans,A_position):
    S1=S[:]
    S2 =S[:]
    S2.pop(0)
    S3 =S2[:]
    S3.pop(0)
    
    
    for i in A_position:
        if S1[i]=="A" and S2[i]=="B" and S3[i]=="C":
            S[i]="B"
            S[i+1]="C"
            S[i+2]="A"
            ans=ans+1
            
    return S,ans

ans=0
for i in range(10000000000):
    if len(S)<2:
        break
        
    flag=ans
    A_position=[i for i, x in enumerate(S1) if x == "A" and i <len(S1)-1]
    S,ans=repABC(S,ans,A_position)
    if flag==ans:
        break
        
print(ans)

Submission status: Runtime Error

Solution code:
S = input()
S = list(S)
onon = True
result = 0
i = 0
back = len(S) + 10
def checkfront(k):
    if k <= 0:
        return 0
    else:
        if S[k - 1] == "A":
            return 1 + checkfront(k-1)
        else:
            return 0

def checkback(k):
    if k >= len(S) - 4:
        return 0
    else:
        if S[k + 3] == "B" and S[k + 4] == "C":
            return 1 + checkback(k+1)
        else:
            return 0

while i <= len(S) - 3:
    if S[i] == "A" and S[i + 1] == "B" and S[i + 2] == "C":
        result += 1
        front = i - checkfront(i)
        if front  == back + 1:
            result += 1
        back = i + 2 + 2 * checkback(i)
        result += checkfront(i)
        result += checkback(i)

    i += 1 
print(result)

Submission status: Runtime Error

Solution code:
A = str(input())
S = [0]*len(A)
for i in range(len(A)):
    if A[i] == "A":
        S[i] = 1
    elif A[i] == "B":
        S[i] = 2
    else:
        S[i] = 3

S.reverse()        
def henkan(S,idx):
    if idx == 0:
        idx = 1
    for i in range(idx-1,len(S)-2):
        if S[i] == 3 and S[i+1] == 2 and S[i+2] == 1:
            S[i] = 1
            S[i+1] = 3
            S[i+2] = 2
            idx = i
            return True
            break
    return False

while (henkan(S,idx)):
    ans += 1
 
print(ans)

Submission status: Runtime Error

Solution code:
dp = 0
def rep(s, r):
    global dp

    if dp < r: dp = r
    if s.find("ABC") < 0:   return r

    i = 0
    while i < len(s):
        s1 = s[:i]
        s2 = s[i:]
        p = s2.find("ABC")
        if p < 0: return r

        rep(s1 + s2.replace("ABC", "BCA", 1), r + 1)
        i = i + 1 + p
    return r

rep(input(), 0)
print(dp)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(1000000)

s = input()

def dfs(st):
  q = st.count('ABC')
  if q < 0:
    return 0
  else:
    st = st.replace('ABC', 'BCA')
    return dfs(st) + q
    
print(dfs(s) if len(s) >= 3 else 0)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
#define il inline
#define elif else if

// Type
#define ld double
#define ll long long
#define ull unsigned ll

// Vector
#define vc vector
#define Pb push_back
#define Pf push_front
#define Eb emplace_back
#define All(x) x.begin(),x.end()
#define AllRev(x) x.rbegin(),x.rend()

// Memory
#define Ms(_data) memset(_data,0,sizeof(_data))
#define Msn(_data,_num) memset(_data,_num,sizeof(_data))

// Template
#define _cl class
#define _tp template
#define _tyn typename

// Pair
#define Mp make_pair
#define F first
#define S second
#define pii pair<int,int>
#define pli pair<ll,int>
#define pil pair<int,ll>
#define pll pair<ll,ll>

// Loop
#define For(i,j) for( int (i) = 1 ; (i) <= (j) ; ++(i) )
#define For0(i,j) for( int (i) = 0 ; (i) < (j) ; ++(i) )
#define Forx(i,j,k) for( int (i) = (j) ; (i) <= (k) ; ++(i) )
#define Forstep(i,j,k,st) for( int (i) = (j) ; (i) <= (k) ; (i) += (st) )
#define fOR(i,j) for( int (i) = (j) ; (i) >= 1 ; --(i) )
#define fOR0(i,j) for( int (i) = (j)-1 ; (i) >= 0 ; --(i) )
#define fORx(i,j,k) for( int (i) = (k) ; (i) >= (j) ; --(i) )

// Read
struct InputReader{
	#define bs 1000001
	char buf[bs]; int p;
	il InputReader(){ p = bs; }
	il void Flush(){ p = 0; fread(buf,1,bs,stdin); }
	il char C(){ if(p >= bs) Flush(); return buf[p++]; }
	il char Readnum(){ char ch = C(); while( !isdigit(ch) && ch != '-' ) ch = C(); return ch; }
	il void Readalpha( char &c ){ c = C(); while( !isalpha(c) ) c = C(); }
	int operator() (){
		int ans = 0, fu = 1; char ch = Readnum();
		if( ch == '-' ) fu = -1, ch = C();
		while( ch >= '0' && ch <= '9' ){
			ans = ans*10 + ch-'0';
			ch = C();
		}
		return ans * fu;
	}
	ll Readll(){
		ll ans = 0LL, fu = 1LL; char ch = Readnum();
		if( ch == '-' ) fu = -1LL, ch = C();
		while( ch >= '0' && ch <= '9' ){
			ans = ans*10LL + ch-'0';
			ch = C();
		}
		return ans * fu;
	}
	il void Readstring( string &x ){
		x.clear(); char ch = C();
		while( !isdigit(ch)  &&  !isalpha(ch)  &&  ch != '#'  &&  ch != '.' ) ch = C();
		while( isdigit(ch)  ||  isalpha(ch)  ||  ch == '#'  ||  ch == '.' ){
			x += ch;
			ch = C();
		}
	}
	il void Readchstring( char s[] ){
		int len = 0; char ch = C();
		while( !isdigit(ch)  &&  !isalpha(ch)  /*&&  ch != '*'  &&  ch != '?'*/ ) ch = C();
		while( isdigit(ch)  ||  isalpha(ch)  /*||  ch == '*'  ||  ch == '?'*/ ){
			s[len++] = ch;
			ch = C();
		}
		s[len] = '\0';
	}
	il void Specialread( char &c ){
		c = C();
		while( !isdigit(c) && !isalpha(c) && c != '#'  &&  c != '.'  &&  c != '='  &&  c != 'B' ) c = C();
	}
	#undef bs
}In;
il void Read( int &x ){ x = In(); }
il void Read( int &x, int &y ){ x = In(); y = In(); }
il void Read( int &x1 , int &x2 , int &x3 ){ x1 = In(); x2 = In(); x3 = In(); }
il void Read( int &x1 , int &x2 , int &x3 , int &x4 ){ x1 = In(); x2 = In(); x3 = In(); x4 = In(); }
il void Read( ll &x ){ x = In.Readll(); }
il void Read( ll &x, ll &y ){ x = In.Readll(); y = In.Readll(); }
il void Read( ll &x1 , ll &x2 , ll &x3 ){ x1 = In.Readll(); x2 = In.Readll(); x3 = In.Readll(); }
il void Read( ll &x1 , ll &x2 , ll &x3 , ll &x4 ){ x1 = In.Readll(); x2 = In.Readll(); x3 = In.Readll(); x4 = In.Readll(); }
_tp<_tyn T> void Read( T a[] , int st , int ed ){ Forx(i,st,ed) Read(a[i]); }
#define iRead(k) int k; Read(k);
#define iRead2(a,b) iRead(a); iRead(b);
#define iRead3(a,b,c) iRead2(a,b); iRead(c);
#define iRead4(a,b,c,d) iRead2(a,b); iRead2(c,d);
#define lRead(k) ll k; Read(k);
#define lRead2(a,b) lRead(a); lRead(b);
#define lRead3(a,b,c) lRead2(a,b); lRead(c);
#define lRead4(a,b,c,d) lRead2(a,b); lRead2(c,d);

// File
#define Fin(a) freopen(a,"r",stdin)
#define Fout(a) freopen(a,"w",stdout)
il void FILEIO(){
	#ifdef intLSY
		Fin("in.in");
	#endif
}
il void FILEIO( string pname ){
	#ifndef intLSY
		Fin((pname+".in").c_str());
		Fout((pname+".out").c_str());
	#else
		Fin("in.in");
	#endif
}
il void FILEIO_OICONTEST( string pname ){
	Fin((pname+".in").c_str());
	#ifndef intLSY
		Fout((pname+".out").c_str());
	#endif
}
void Printtime(){
	#ifdef intLSY
		double _timeuse = clock()* 1000.0 / CLOCKS_PER_SEC;
		fprintf(stderr,"\n\nTime usage:\n%.0lf ms\n",_timeuse);
	#endif
}
void END(){ Printtime(); exit(0); }
_tp<_tyn T>void END( T mes ){ cout << mes << endl; END(); }

// Debug
#define B cerr << "BreakPoint" << endl;
#define O(x) cerr << #x << " " << x << endl;
#define O_(x) cerr << #x << " " << x << "  ";
#define ERR(x) cerr << "ERR! #" << x << endl;
#define Msz(x) cerr << "Sizeof " << #x << " " << sizeof(x)/1024/1024 << " MB" << endl;
_tp<_tyn T>void Print( T a[] , int s , int t , char sp = ' ' , char ed = '\n' ){
	if( s > t ) return;
	for( int i = s ; i < t ; i++ )
		cout << a[i] << sp;
	cout << a[t] << ed;
	cout.flush();
}
_tp<_tyn T>void Print( T a , int s = 0 , int t = -1 , char sp = ' ' , char ed = '\n' ){
	if( t == -1 ) t = a.size()-1;
	for( int i = s ; i <= t ; i++ )
		cout << a[i] << sp;
	cout << ed;
	cout.flush();
}

// Optimize
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define Mymax(a,b) (a) = max((a),(b))
#define Mymin(a,b) (a) = min((a),(b))
#define INF (0x3f3f3f3f)
#define LINF ((long long)(0x3f3f3f3f3f3f3f3f))
#define Sqr(x) ((x)*(x))
vc<int> Range( int l , int r ){
	vc<int> ret{};
	Forx(i,l,r) ret.Pb(i);
	return ret;
}

///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
int n;

int main(){
	FILEIO();

	string s;
	cin >> s;
	n = s.length();

	static int col[262144];

	For0(i,n){
		if( s[i] == 'A' ) col[i] = 0;
		else{
			if( s[i] == 'B' ){
				if( i != n-1 and s[i+1] == 'C' ){
					col[i] = 1;
					col[i+1] = 2;
				}
				else col[i] = -1;
			}else{
				if( i != 0 and s[i-1] == 'B' ){
					col[i-1] = 1;
					col[i] = 2;
				}
				else col[i] = -1;
			}
		}
	}

	ll ans = 0;
	int acnt = 0;
	For0(i,n){
		if( col[i] == -1 ){
			acnt = 0;
			continue;
		}
		if( col[i] == 1 ){
			ans += acnt;
		}elif( col[i] == 0 ){
			++acnt;
		}
	}
	cout << ans << endl;

	END();
}

Submission status: Runtime Error

Solution code:
# %%time
s = input()

k = 0
kk = 0
ans = 0
while True:
    
    if k >= len(s) - 1:
        break
    if s[k : k + 3] == "ABC":
        n = 0
        while True:
            if s[k + 3 + n  *2 : k + 5 + n * 2] == "BC":
#                 aaa
                if s[k + 3 + n * 2 > len(s)]:
                    break
                n += 1
            else:
                break
                
        m = 0
        while True:
            ind = k-m-1
            if ind  < 0:
                break
            if s[ind] == "A":
                m+=1
            else:
                break

        if n == 0:                
            while True:
                if k + 3 + j * 3 > len(s):
                    break
#                 print(s[k + 3 + j  *3 : k + 6 + j * 3])
                if s[k + 3 + j  *3 : k + 6 + j * 3] == "ABC":
                    j += 1
                else:
                    break
            s = s[:k] + "BC" * (j + 1) + "A" * (j + 1) + s[k+3 + j * 3:]
            kk = k + j * 3
            kk = k
            k -= 1
            print(j)
            ans += (j + 2) * (j + 1) // 2
            
        else:
            s = s[:k-m] + "BC" * (n + 1) + "A" * (m + 1) + s[k+3 + n * 2:]        
            kk = k + m  + n * 2
            kk = k
            k -= 1
            ans += (n + 1) * (m + 1)
        
#         print(s)
#         aaaa
    else:
#         print(k)
        k += 1
        if kk > k:
            k = kk

print(ans)

Submission status: Runtime Error

Solution code:
import re

count = int(0)
txt = input()

def rewrite(pat,txt):
    m = re.search(pat,txt)
    if m != None:
        txt_list = list(txt)
        txt_list[m.start()] = 'B'
        txt_list[m.start()] = 'C'
        txt_list[m.end()] = 'A'
        txt = "".join(txt_list)
    return m

while True:
    if rewrite('ABC',txt) is None:
        break
    else:
        count += 1 is None:
        break

print(count)

Submission status: Runtime Error

Solution code:
S = list(input())
S = S[::-1]

t = 0
ans = 0
bc_score = 0
flag = 1

if len(S) <= 2:
    print(0)
    exit()

while t <= len(S)-1:
    if S[t]=="C" and S[t+1] == "B":
        bc_score = 0
        bc_score += 1
        t += 2
        flag = 1
        if t == len(S)-1:
            if S[t] == "A":
                ans += 1
            t += 1
        while flag == 1 and t < len(S) - 1:
            flag = 0
            if S[t]=="C" and S[t+1] == "B":
                bc_score += 1
                t += 2
                flag = 1
            if t <= len(S) - 1:
                if S[t] == "A":
                    ans += bc_score
                    t += 1
                    flag = 1
    else:
        t += 1

print(ans)

Submission status: Runtime Error

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

qS = input()


def replace(s, count):
    matches = re.finditer('ABC', s)
    max_count = count
    for m in matches:
        m.span()
        max_count = max(max_count, replace(
            s[:m.span()[0]] + 'BCA' + s[m.span()[1]:], count + 1))
    return max_count


print(replace(qS, 0))

Submission status: Runtime Error

Solution code:
import sys

def check(abc_lst, idx, cnt):
    if abc_lst[idx:idx+3] == [1,2,3]:
        cnt += 1
        abc_lst[idx] = 2
        abc_lst[idx+1] = 3
        abc_lst[idx+2] = 1
        if idx > 0 and abc_lst[idx-1] == 1:
            cnt = check(abc_lst, idx-1, cnt)
    if idx < len(abc_lst) - 2:
        cnt = check(abc_lst, idx+1, cnt)
    return cnt

sys.setrecursionlimit(10**9)

S = input()
ABC_dict = {'A':1, 'B':2, 'C':3}
abc_lst = [ABC_dict[S[i]] for i in range(len(S))]
print(check(abc_lst, 0, 0))

Submission status: Runtime Error

Solution code:
S = input()
S = list(S)
onon = True
result = 0
i = 0
back = len(S) + 10
def checkfront(k):
    if k <= 0:
        return 0
    else:
        if S[k - 1] == "A":
            return 1 + checkfront(k-1)
        else:
            return 0

def checkback(k):
    if k >= len(S) - 4:
        return 0
    else:
        if S[k + 3] == "B" and S[k + 4] == "C":
            return 1 + checkfront(k+1)
        else:
            return 0

while i <= len(S) - 3:
    if S[i] == "A" and S[i + 1] == "B" and S[i + 2] == "C":
        result += 1
        front = i - checkfront(i)
        if front  == back + 1:
            result += 1
        back = i + 2 + 2 * checkback(i)
        result += checkfront(i)
        result += checkback(i)

    i += 1 
print(result)

Submission status: Runtime Error

Solution code:
s = input()

cnt = 0
x = 0
while x <=len(s):
    print(s)
    if s[x:x+3] == "ABC":
        s = s[:x]+"BCA"+s[x+3:]
        cnt += 1
        for y in range(0,len(s),2):
            if s[x+3+y:x+5+y] == "BC":
                s = s[:x+5+y-3]+"BCA"+s[x+5+y:]
                cnt += 1
            else:
                break
        if x>0:
            for z in range(1,len(s)):
                if s[x-z] == "A":
                    s = s[:x-z]+"BCA"+s[x-z+3:]
                    cnt += 1
                else:
                    break
        x += 3
    else:
        x += 1
print(cnt)

Submission status: Runtime Error

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

qS = input()

counts = {}


def replace(s, count):
    if counts.get(s, -1) >= 0:
        return counts[s]
    else:
        matches = re.finditer('ABC', s)
        max_count = count
        for m in matches:
            m.span()
            max_count = max(max_count, replace(
                s[:m.span()[0]] + 'BCA' + s[m.span()[1]:], count + 1))
        counts[s] = max_count
        return counts[s]


print(replace(qS, 0))

Submission status: Runtime Error

Solution code:
N, A, B, C, D = [int(i) for i in input().split()]
S = input()

def solve():
    ac, bd = S[A - 1:C], S[B - 1:D]
    if A < B < D < C:
        bd = S[B - 2:D + 1]
        return ("..." in bd and "##" not in ac)
    else:
        return ("##" not in ac and "##" not in bd)

if solve():
    print("Yes")
else:
    print("No")