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: Time Limit Exceeded

Solution code:
import re
base_str = input()
exp = "(A+)(BC)+"
flg = True
res = 0
tmp_end = 0
tmp_A = 0
for m in re.finditer(exp, base_str):
  A_len = len(m.group(1)) 
  if tmp_end == m.start(0):
    A_len += tmp_A
  match_str = m.group(0)
  trans_num = A_len * (len(m.group(0)) - len(m.group(1))) / 2
  res += int(trans_num)
  tmp_end = m.end(0)
  tmp_A = A_len
print(res)

Submission status: Time Limit Exceeded

Solution code:
ST = input()
S = list(ST)
search_char = 2
count = 0

while(search_char != len(ST) and search_char <= len(ST)):
    if S[search_char - 2] + S[search_char - 1] + S[search_char] == "ABC":
        S[search_char-2] , S[search_char - 1] , S[search_char] ="B", "C", "A"
        search_char = max(search_char - 1, 2)
        count += 1
    else:
        if S[search_char - 1] == 'A':
            search_char += 1
        elif S[search_char] == 'A':
            search_char += 2
        else:
            search_char += 3
print(count)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# agc034/agc034_b
import sys

i2s = lambda: sys.stdin.readline().rstrip()

def main():
    S = list(i2s())
    N = len(S)
    flag = True
    cnt = 0
    while flag:
        flag = False
        i = 0
        while i < N - 2:
            if S[i:i+5] == ['A', 'B', 'C', 'B', 'C']:
                flag = True
                cnt += 2
                S[i:i+5] = ['B', 'C', 'B', 'C', 'A']
                i += 4
            elif S[i:i+4] == ['A', 'A', 'B', 'C']:
                flag = True
                cnt += 2
                S[i:i+4] = ['B', 'C', 'A', 'A']
                i += 3
            elif S[i:i+3] == ['A', 'B', 'C']:
                flag = True
                cnt += 1
                S[i:i+3] = ['B', 'C', 'A']
                i += 2
            else:
                i += 1
    print(cnt)
    return

main()

Submission status: Time Limit Exceeded

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

cnt = 0
cnti = 0
cntj = 0
i = 0
while True:
    while True:
        if 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
            break
        i += 1
    if cnti > 2:
        break
print(cnt)

Submission status: Time Limit Exceeded

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

def conv2num(c):
    if c == "A":
        return 1
    elif c == "B":
        return 2
    else:
        return 3

def solve(s: str):

    res = 0

    s = [ conv2num(c) for c in s ]
    i = 0
    endi = len(s) - 2
    while i < endi:
        if s[i] == 1 and s[i+1] == 2 and s[i+2] == 3:
            ai = i
            for j in range(i-1,-1,-1):
                if s[j] == 1 and j >=0 :
                    ai = j 
                else:
                    break
            s[ai]   = 2
            s[ai+1] = 3
            s[ai+2] = 1
            res += 1

            st = ai+3
            ed = i +3
            if st != ed:
                for k in range(st,ed):
                    s[k] = 1
                    res += 1
            i += 1
        i += 1

    print(res)

    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()
    s = next(tokens)  # type: str
    solve(s)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
s=input()

cnt=0
while(True):
  if s.find("ABC") == -1:
    break
  else:
    s = s.replace("ABC","BCA",1)
    cnt += 1
    
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
s = list(input())
l = len(s)
count = 0
past = 0
while True:
  for i in range(l-2):
    if s[i:i+3] == ['A','B','C']:
      count += 1
      s[i:i+3] = ['B','C','A']
  if count == past:
    break
  past = count
print(count)

Submission status: Time Limit Exceeded

Solution code:
def li():
    return list(map(int, input().split()))


if __name__ == "__main__":
    s = input()
    ope_num = 0
    index = 0
    a_stock = 0
    b_stock = 0
    s = list(s)
    while index < len(s):
        # print(s)
        # print(index)
        # print(ope_num)
        # print()
        si = s[index]
        if si == "A":
            if b_stock > 0:
                a_stock = 1
            else:
                a_stock = a_stock + 1
            b_stock = 0
        elif a_stock > 0:
            if si == "B" and b_stock == 0:
                b_stock = 1
            elif si == "C" and b_stock > 0:
                ope_num = ope_num + a_stock
                s[index - 2 - a_stock + 1] = "B"
                s[index - 1 - a_stock + 1] = "C"
                for i in range(a_stock - 1, -1, -1):
                    s[index - i] = "A"
                index = index - a_stock
                a_stock = 0
                b_stock = 0
            else:
                a_stock = 0
                b_stock = 0
        else:
            a_stock = 0
            b_stock = 0
        index = index + 1
    print(ope_num)

# ABCの数
# ABCの前にあるAの分だけ追加で操作できる
# ABCの後にある(BC)の分だけ追加で操作できる

# Aがあれば覚えておく
# ABCと来たら、それより前側に隣接しているAの回数だけ追加で操作できる
# 見つかったABCをBCAに置き換える
# BCAのAから走査を継続する

Submission status: Time Limit Exceeded

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

cnt = 0
cnti = 0
cntj = 0
i = 0
while True:
    while True:
        if 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:
            i = 0
            cnti += 1
            cntj += 1
            break
        i += 1
    if cnti > 2:
        break
print(cnt)

Submission status: Time Limit Exceeded

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
idx = 0
ans = 0
while (henkan(S,idx)):
    ans += 1
 
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

S=input()
if len(S)<2: print(0),sys.exit()
elif len(S)==3:
    print(1 if S=="ABC" else 0)
    sys.exit()

s=[]
a=[]
x=ord("A")
for i in range(len(S)):
    s.append(ord(S[i])-x)
    if S[i]=="A": a.append(i)
a=[a[i] for i in range(len(a)-1,-1,-1)]


tmp=0
abc,bca=[0,1,2],[1,2,0]
ans=0
while True:
    if a==[] or a[-1]>=len(s)-2: break
    tmp=a[-1]
    if s[tmp:tmp+3]==abc:
        s[tmp:tmp+3]=bca
        a.append(tmp+2)
        if tmp>0: a.append(tmp-1)
        ans+=1
    else: a.pop(-1)

print(ans)

Submission status: Time Limit Exceeded

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: Time Limit Exceeded

Solution code:
S = []
C = []
S.append(-1)
p2 = -1
p1 = -1
for idx,s in enumerate(input()):
  if s == 'A':
    a = 1
  if s == 'B':
    a = 2
  if s == 'C':
    a = 3
    
  if p2 == 1 and p1 == 2 and a == 3:
    C.append(idx)
  
  p2 = p1
  p1 = a
  S.append(a)

S.append(-1)

def sss(Sin, Cin):
  NC = []
  for c in Cin:
    Sin[c-1] = 2
    Sin[c] = 3
    Sin[c+1] = 1
    if Sin[c-2] == 1 and Sin[c-1] == 2 and Sin[c] == 3:
      NC.append(c-1)
    if Sin[c+1] == 1 and Sin[c+2] == 2 and Sin[c+3] == 3:
      NC.append(c+2)
      
  #print(Sin)
  #print(NC)
  return NC

CA = 0
NC = C
while len(NC) > 0:
  CA += len(NC)
  NC = sss(S,NC)
  
print(CA)

Submission status: Time Limit Exceeded

Solution code:
import re

S = str(input())
k=int(0)

#for i in range(2000):
#while () :
a = int(1)
while a!=0:
#    S = S[:S.rfind('ABC')] + 'BCA' + S[(S.rfind('ABC')+3):]
#    k +=1
    a = len(re.findall("ABC",S))
    k += a
    S = S.replace('ABC', 'BCA')
#    if a==0 : break

print(int(k))

Submission status: Time Limit Exceeded

Solution code:
s=input()
S=""
i=0
leng=len(s)
while(i<leng):
    if s[i]=="A":
        S+="A"
        i+=1
    elif i+1<leng and s[i:i+2]=="BC":
        S+="B"
        i+=2
    else:
        S+="C"
        i+=1
T=S[::-1]
l=[0]*len(T)
ans=0
t=len(T)
for i in range(len(T)-1):
    if T[i]=="B":
        l[i+1]=l[i]+1
    elif T[i]=="A":
        l[i+1]=l[i]
        ans+=l[i]
if T[-1]=="A":
    ans+=l[-1]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

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

    ans = 0
    cnt = 0
    i = 0
    while i < n:
        if S[i:i+3] == 'ABC':
            cnt += 1 
            T += 'BCA'

            i += 3
        else:
            T += S[i]
            i += 1

    ans += cnt
    while cnt > 0:
        cnt = 0
        S = T
        T = ''
        i = 0
        while i < n:
            if S[i:i+3] == 'ABC':
                cnt += 1
                T += 'BCA'
                i += 3
            else:
                T += S[i]
                i += 1

        ans += cnt

    return ans


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

Submission status: Time Limit Exceeded

Solution code:
S = input()

cnt = 0
while True:
    updated = S.replace('ABC', 'BCA', 1)
    if updated == S:
        print(cnt)
        break
    cnt += 1
    S = updated

Submission status: Time Limit Exceeded

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

cnt = 0
cnti = 0
i = 0
while True:
    while True:
        if 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:
                break
        elif i >= len(s)-2:
            i = 0
            cnti += 1
            break
        i += 1
    if cnti > 2:
        break
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
s = input()
s_long = len(s)
kaisu = 0
check = 0
while 1:
    if check > s_long - 3:
        print(kaisu)
        break
    if s[check:check+3] == 'ABC':
        s = s[:check] + 'BCA' + s[check+3:]
        kaisu += 1
        check += 2
        i = check - 3
        while 1:
            if i < 0:
                break
            else:
                if s[i] != 'A':
                    break
                else:
                    s = s[:i] + 'BCA' + s[i+3:]
                    kaisu += 1
                    i -= 1
    else:
        check += 1

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg 
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():
	st=[]
	s=f4()
	n1=0
	ans=0
	for i in s:
		n1+=1
		st.append(i)
		if i=="C" and n1>=3:
			s1=[]
			n2=n1-1
			for i in xrange(3):
				s1.append(st[n2])
				n2-=1
			s1=s1[::-1]
			if s1==["A","B","C"]:
				ans+=1
				st[n1-1]="A"
				while n2>-1 and st[n2]=="A":
					ans+=1
					st[n2+2]="A"
					n2-=1
				st[n2+1],st[n2+2]="B","C"
	print ans


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
S=input()
ans=0
for _ in range(len(S)):
    v = S.count('ABC') 
    if v>0:
        ans += v
        S=S.replace('ABC','BCA')
    else:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = input()
s=list(s)
max=0
while True:
    max_b=max
    for i in range(len(s)-2):
        if s[i]=='A':
            if s[i+1] == 'B':
                if s[i+2] == 'C':
                    s[i]='B'
                    s[i+1] = 'C'
                    s[i+2] = 'A'
                    max=max+1
    if max_b==max:break
print(max)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()


def main():
    s = read()
    ans = 0
    st = []
    for ch in s:
        st.append(ch)
        if len(st) >= 3 and st[-3:] == ['A', 'B', 'C']:
            st.pop()
            st.pop()
            st.pop()
            c = 1
            while st and st[-1] == 'A':
                c += 1
                st.pop()
            ans += c
            st = list('A'*c)
    print(ans)


def slow(s):
    ans = 0
    while True:
        x = s.count('ABC')
        if x:
            ans += x
            s = s.replace('ABC', 'BCA')
        else:
            break
    return ans

# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")


def read():
    return input()


def read_array(sep=None, maxsplit=-1):
    return read().split(sep, maxsplit)


def read_int():
    return int(read())


def read_int_array(sep=None, maxsplit=-1):
    return [int(a) for a in read_array(sep, maxsplit)]

# endregion

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    s=input()
    n = len(s)
    cum = [0] * (n+1)
    sr = s[::-1]
    for i in range(n-1):
        if sr[i] == 'C' and sr[i+1] == 'B':
            cum[i+1] = cum[i] + 1
        elif sr[i] == 'A' or sr[i:i+2] in ['BC'] or (0 < i and sr[i-1:i+2] == 'CBA'):
            cum[i+1] = cum[i]
        else:
            cum[i+1] = 0
    cum[n] = cum[n-1]
    ans = 0
    for i in range(n):
        if s[i] != 'A':
            continue
        ans += cum[n-i-1]

    if n < 1000:
        print(ans)
        return

    flag = True
    s = [i for i in s]
    ans = 0
    while flag:
        flag = False
        for i in range(n-2):
            if s[i:i+3] == ['A', 'B', 'C']:
                s[i] = 'B'
                s[i+1] = 'C'
                s[i+2] = 'A'
                flag = True
                ans += 1

    print(ans)
    
main()

Submission status: Time Limit Exceeded

Solution code:
s = input().strip()
ret = 0
while 'ABC' in s:
    ret += s.count('ABC')
    s = s.replace('ABC', 'BCA')
print(ret)

Submission status: Time Limit Exceeded

Solution code:
# %%time
s = input()
# s = "ABC" * 10000


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:       
            j = 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
            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: Time Limit Exceeded

Solution code:
import re

S = str(input())
k=int(0)

#for i in range(2000):
#while () :
while S.find('ABC')>=0:
#    S = S[:S.rfind('ABC')] + 'BCA' + S[(S.rfind('ABC')+3):]
#    k +=1
    k += len(re.findall("ABC",S))
    S = S.replace('ABC', 'BCA')
#    if a==0 : break

ans = (int(k))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

fin = sys.stdin.readline
s_abc = fin().split()[0]

end_flag = True
count = 0
while end_flag:
    if 'ABC' not in s_abc:
        end_flag = False
    count += s_abc.count('ABCBCAABC') * 5
    s_abc = s_abc.replace('ABCBCAABC', 'BCBCBCAAA')
    count += s_abc.count('ABC')
    s_abc = s_abc.replace('ABC', 'BCA')

print(count)

Submission status: Time Limit Exceeded

Solution code:
s=input()
n=len(s)

maxcnt=0
def exec(string,cnt):
    global maxcnt
    for i in range(n-2):
        if i<n-4:
            if string[i:i+5]=="ABCBC":
                return exec(string[0:i]+"BCBCA"+string[i+5:],cnt+2)
        if i<n-3:
            if string[i:i+4]=="AABC":
                return exec(string[0:i]+"BCAA"+string[i+4:],cnt+2)
        
        if string[i:i+3]=="ABC":
            exec(string[0:i]+"BCA"+string[i+3:],cnt+1)
            
    if maxcnt<cnt:
        maxcnt=cnt

exec(s,0)
print(maxcnt)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
import re

s = stdin.readline().rstrip()
rex = r"ABC"
cnt = 0
x = re.findall(rex, s)
while len(x) > 0:
    cnt += len(re.findall(rex, s))
    s = s.replace('ABC', 'BCA')
    x = re.findall(rex, s)

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
S = []
C = []
S.append(-1)
p2 = -1
p1 = -1
for idx,s in enumerate(input()):
  if s == 'A':
    a = 1
  if s == 'B':
    a = 2
  if s == 'C':
    a = 3
    
  if p2 == 1 and p1 == 2 and a == 3:
    C.append(idx)
  
  p2 = p1
  p1 = a
  S.append(a)
  
S.append(-1)

def sss(Sin, Cin):
  NC = []
  for c in Cin:
    Sin[c-1] = 2
    Sin[c] = 3
    Sin[c+1] = 1
    if Sin[c-2] == 1 and Sin[c-1] == 2 and Sin[c] == 3:
      NC.append(c-1)
    if Sin[c+1] == 1 and Sin[c+2] == 2 and Sin[c+3] == 3:
      NC.append(c+2)
      
  #print(Sin)
  #print(NC)
  return Sin, NC

CA = 0
NC = C
NS = S
while len(NC) > 0:
  CA += len(NC)
  NS,NC = sss(NS,NC)
  
print(CA)

Submission status: Time Limit Exceeded

Solution code:
s = input()

num = 0
while True:
  r = s.find("ABC")
  
  if r >= 0:
    num += 1
    s = "".join([s[:r] + "BCA" + s[r+3:]])
  else:
    break

print(num)

Submission status: Time Limit Exceeded

Solution code:
s = input()

p = []
for i in range(len(s)):
    p.append(s[i])

p.reverse()

ret = 0
i = 0
while i < len(s) -2: 
    if p[i] == "C":
        if p[i+1] == "B":
            if p[i+2] == "A":
                p[i] = "A"
                p[i+1] = "C"
                p[i+2] = "B"
                i = i - 3
                ret += 1
    i += 1
        
print(ret)

Submission status: Time Limit Exceeded

Solution code:
#
#　　　　　　　　　　　　　　,. -─────────‐- .、
#　　　　　　　　　　　　 ／／￣￣＼　　　　　　／￣￣＼＼
#　　　　　　　　　　　／　　　　　　　　　　　　　　　　　　　　 ＼
#　　　　　　　　　 ／　　　　　　　　::::::::::::::::::::::::::::::::　　　　　　　＼
#　　　　　　　　／ 　　／ ／￣＼＼::::;;;;;;;;;;;;;;;;;:::::／／￣＼＼　　＼
#　　　　　　 ／　　　　|　 |.　┃　.|　| ::::;;;;;;;;;;;;;::::｜ |.　┃　.|　|　　　 ＼　　　　　　　　　　　　　　　　　　　　　
#　　　　　／ 　　　　　＼ ＼＿／／　::::::::::::::::::　＼＼＿／／　　　　　 ＼　　　　
#　　　 ／　　　　　..／￣￣＼　／　　　::｜::　　　＼　／￣￣＼..　　　　　＼
#　　 / 　 　 　 　 :::::　　　　　　|　　　　　 |　　　　　 |　　　　　　 :::::　　　　　 ヽ.　　　
#　　| 　　　　　　　　　　　　　　|　　　　　 |　　　　　 |　　　　　　　　　　　　　　|.
#　　| 　　　　　　　　　　　　　　＼＿＿／＼＿＿／ 　　　　　　　　　　　　　　|　　　　　　　　　　　　　　　　　
#　　| 　　　　　　　　　　　　　　　｜　　　　　　　｜　　　　　　　　　　　　　　　|
#　　| 　　　　　　　　　　　　　　　｜r─‐┬──､|　　　　　　　　　　　　　　　 |
#　　ヽ　　　　　　　　　　　　　　　 |/　　　|　　 　｜　　　　　　　　　　　　　　/
#　　　 ＼　　　　　　　　　　　　　 ＼　　　　　　／　　　　　　　　　　　　　／
#　　　　　＼ 　　　　　　　　　　　　　￣￣￣￣　　　　　　　　　　　　　／
#
#
import sys
input=sys.stdin.readline
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [input() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    s = ST()
    S = list(s)
    cnt=0
    for i in range(len(S)-2)[::-1]:
        if S[i:i + 3] == list("ABC"):
            S[i:i + 3] = list("BCA")
            cnt += 1
            while i!=len(S)-2:
                if S[i+2:i + 5] == list("ABC"):
                    S[i+2:i +5] = list("BCA")
                    cnt += 1
                    i+=2
                else:
                    break
                #print("while", S)
        #print("for","".join(S))
    print(cnt)

    """    #愚直解
    frag = True
    cnt=0
    while frag:
        frag = False
        for i in range(len(S) - 2)[::-1]:
            if S[i:i + 3] == list("ABC"):
                frag = True
                cnt+=1
                S[i:i + 3] = "BCA"
    print(cnt) """"""
    ans=0
    while 1:
        c = s.count("ABC")
        if c == 0:
            break
        ans += c
        s=s.replace("ABC", "BCA")
    print(ans)
    """"""
    ans=0
    while index < len(S):
        if S[index] == A:
            bcindex =index+1
            while bcindex < len(S)-1:
                if S[bcindex:bcindex + 2] == list("BC"):
                    ans += 1
                    bcindex += 2
                    frag = True
                else:
                    break
            if frag:
                index = bcindex - 1
                S[index]="A"
            else:
                index = bcindex         
        index +=1
"""
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
S=list(input())

def repABC(S,ans):
    S1=S[:]
    S2 =S[:]
    S2.pop(0)
    S3 =S2[:]
    S3.pop(0)
    
    A_position=[i for i, x in enumerate(S1) if x == "A" and i <len(S1)-2]
        
    #print(A_position)
    
    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
    S,ans=repABC(S,ans)
    if flag==ans:
        break
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()


def main():
    s = read()
    ans = 0
    st = []
    for ch in list(s):
        st.append(ch)
        if len(st) >= 3 and st[-3:] == ['A', 'B', 'C']:
            st.pop()
            st.pop()
            st.pop()
            c = 1
            while st and st[-1] == 'A':
                c += 1
                st.pop()
            st.append('B')
            st.append('C')
            ans += c
            for _ in range(c):
                st.append('A')
    print(ans)


def slow(s):
    ans = 0
    while True:
        x = s.count('ABC')
        if x:
            ans += x
            s = s.replace('ABC', 'BCA')
        else:
            break
    return ans

# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")


def read():
    return input()


def read_array(sep=None, maxsplit=-1):
    return read().split(sep, maxsplit)


def read_int():
    return int(read())


def read_int_array(sep=None, maxsplit=-1):
    return [int(a) for a in read_array(sep, maxsplit)]

# endregion

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
s = list(input())
ans = 0
ls = len(s)
i = 0
while i < ls-2:
    if s[i:i+3] == ['A', 'B', 'C']:
        ans += 1
        s[i:i+3] = ['B', 'C', 'A']
        i -= 1
        continue
    i += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = input()

num = 0
while True:
  r = s.find("ABC")
  
  if r >= 0:
    num += 1
    s = s[:r] + "BCA" + s[r+3:]
  else:
    break

print(num)

Submission status: Time Limit Exceeded

Solution code:
s = list(input())
check = []
# a = []
for i in range(len(s)):
    if i < len(s)-1 and s[i]=='B' and s[i+1]=='C':
        check.append(1)
    else:
        check.append(0)
# print(check)
# for i in range(len(s)):
#     if


count = 0
for i in range(len(s)):
    if s[-i-1] == 'A':
        # a.insert(0, 1)
        tmp = -i-1
        while tmp <= -3 and check[tmp+1]==1:
            # s.pop(tmp)
            # s.insert(tmp+3, 'A')
            check[tmp+1] = 0
            check[tmp] = 1
            # s[tmp+1] = 'C'
            # s[tmp+2] = 'A'
            count += 1
            tmp += 2
print(count)

Submission status: Time Limit Exceeded

Solution code:
s=input()
c=0
while ('ABC' in s):
	c+=s.count('ABC')
	s=s.replace('ABC','BCA')
	s=s[s.index('A')::]
print(c)

Submission status: Time Limit Exceeded

Solution code:
import re
s = input()
l = list(map(str, s))
c = 0

x=0
if  ''.join(l).find('ABC') != -1:
    x = 1

while x == 1:
    for i in range(len(l)):
        if i <= len(l)-3:
            if l[i:i+3] == ['A', 'B', 'C']:
                c += 1
                l[i:i+3] = ['B', 'C', 'A']
    if ''.join(l).find('ABC') != -1:
        x = 1
    else :
        x=0

    
print(c)

Submission status: Time Limit Exceeded

Solution code:
import re

s = input()

count = 0
while 1:
  if re.search("ABC", s):
    s = s.replace("ABC", "BCA", 1)
    count += 1
  else:
    print(count)
    break

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)

s = input()

def dfs(st):
  q = st.find('ABC')
  if q < 0:
    return 0
  else:
    st = st[:q]  + 'BCA' + st[q+3:]
    return dfs(st) + 1
    
print(dfs(s) if len(s) >= 3 else 0)

Submission status: Time Limit Exceeded

Solution code:
s=input()


i=0
c=0
flag=0
while True:
	if i>len(s)-3: break
	if s[i:i+3]=="ABC":
		j=i
		d=0
		while True:
			if j<0: break
			if s[j]=="A":
				d+=1
				j-=1
			else: break
		s=s[:i-d+1]+"BC"+"A"*d+s[i+3:]
		c+=d
		i+=1
		continue
	else: i+=1

print(c)

Submission status: Time Limit Exceeded

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

import sys
import re

s= sys.stdin.readline().strip()
#
c= 0
pat= re.compile("(A+)((BC)+)")
while True:
    m =pat.search( s )
    if not m: break
    n = len( m.group(0) )
    a = len( m.group(1) )
    bc= len( m.group(2) ) // 2
    s= ("A"*a) + s[m.end():]
    c+= a*bc
print( c )