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
while(flg):
  m = re.search(exp, base_str)
  if m is None:
    flg = False
  else:
  	match_str = m.group(0)
  	trans_num = len(m.group(1)) * len(m.group(2)) / 2
  	res += int(trans_num)
  	replace_str = "BC" * int(len(m.group(2)) / 2) + "A" * len(m.group(1))
  	base_str = replace_str + base_str[m.end(0):]
print(res)

Submission status: Time Limit Exceeded

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

while ''.join(l).find('ABC') != -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']
    
print(c)

Submission status: Time Limit Exceeded

Solution code:
import sys
import re
sys.setrecursionlimit(10 ** 7)


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def SI(): return input()


def main():
    S = SI()
    ans = 0
    now = 0
    while(1):
        now = S.find("ABC")
        if now == -1:
            break
        ans += 1
        i = 1
        aa = 0
        while(S[now-i] == 'A' and now-i >= 0):
            ans += 1
            i += 1
            aa += 1
        # S = S[a+3:]
        bc = 0
        now += 3
        while(S[now:now+2] == "BC"):
            ans += 1
            now += 2
            bc += 1
        ans += aa*bc
        S = "A"*(aa+1) + S[now:]
    print(ans)


main()

Submission status: Time Limit Exceeded

Solution code:
m=input()
s_list=list(m)
count=0
while m.find('ABC')!=-1:
    m_s=m.find("ABC")
    s_list[m_s:m_s+3]=["B","C","A"]
    count+=1
    m=""
    for x in s_list:
        m+=x         
print(count)

Submission status: Time Limit Exceeded

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:
        s=S.pop(0)

        if s=="A":
            a+=1
            b=False
        elif s=="B":
            if b:
                b=False
                a=0
            else:
                b=True
        else:
            if b:
                out+=a
                for _ in range(a):
                    S.insert(0, "A")
            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: Time Limit Exceeded

Solution code:
s =  [0] + [ord(i) for i in input()]

ret = 0
i = 0

while i < len(s) :
    if s[i:i+3] == [65, 66, 67] :
        s[i:i+3] = [66, 67, 65]
        ret += 1
        i -= 1
    else :
        i += 1

print(ret)

Submission status: Time Limit Exceeded

Solution code:
s = input()
lst = list(s)

cnt = 0
madaikeru = True
while madaikeru:
    if len(s) < 3:
        madaikeru = False
    else:
        for i in range(len(s)-2):
            if lst[i]=='A' and lst[i+1]=='B' and lst[i+2]=='C':
                lst[i] = 'B'
                lst[i+1] = 'C'
                lst[i+2] = 'A'
                cnt += 1
                break
            if i == len(s)-3:
                madaikeru = False

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
ST = input()

def changeABC2BCA(ST):
    S = [s for s in 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 - 4, 2)
            count += 1
        else:
            search_char += 1
    
    return count
  
print(changeABC2BCA(ST))

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)
    for i in range(len(S3)):
        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
            break
    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:
S = list(input())

count = 0
tmp_list = list(range(len(S)-2))

while tmp_list != []:
    new_list = []
    for i in set(tmp_list):
        if "".join(S[i:i+3]) == "ABC":
            count += 1            
            S[i:i+3] = ["B", "C", "A"]
            
            if i-1 >= 0:
                new_list.extend([i-1, i+2])
            else:
                new_list.extend([i+2])
    tmp_list = new_list

print(count)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

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


def choose_abc_range(s):
    ranges = []
    cur = 0
    while cur < len(s):
        if s[cur:cur+3] == "ABC":
            st = cur
            j = cur

            while s[j:j+3] == "ABC":
                j += 3

            ed = j

            ranges.append([st, ed])
            cur = j

        else:
            cur += 1

    return ranges

def get_a(sa):
    a = 0
    for sai in sa:
        if sai == "A":
            a += 1
        else:
            break

    return a

def get_bc(sb):
    b = 0
    for sbi in sb[::2]:
        if sbi == "bc":
            b += 1
        else:
            break

    return b

s = ns()
ans = 0
while "ABC" in s:

    ranges = choose_abc_range(s)
    for l, r in ranges:
        k = (r-l+1)//3
        a = get_a(s[l-1::-1])
        b = get_bc(s[r:])

        ans += k*(k+1)//2 + max(a*k + b*(k+a), b*k, a*(k+b))

        s = s[:l-a] + "BC"*(k+b) + "A"*(k+a) + s[r+2*b:]

print(ans)

Submission status: Time Limit Exceeded

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


def solve(s: str):

    res = 0

    s = list(s)
    for i in range(len(s)-2):
        if s[i] == "A" and s[i+1] =="B" and s[i+2] =="C":
            ai = -1
            for j in range(i-1,-1,-1):
                if j >=0 and s[j] == "A":
                    ai = j 
                else:
                    break
            if ai >= 0:
                s[ai]   = "B"
                s[ai+1] = "C"
                s[ai+2] = "A"

                res += 1
                for k in range(ai+3,i+3):
                    s[k] = "A"
                    res += 1
            else:
                s[i]   = "B"
                s[i+1] = "C"
                s[i+2] = "A"
                res += 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:
import sys
INPUT = sys.stdin.readline
S = list(input())
S.reverse()
L = len(S)
A, B, C = 'A', 'B', 'C'

followingAs = 0
searchABC = 0
ans = 0

while S:

    last = S.pop()

    if last == A:
        if searchABC == 0:
            searchABC = 1
            followingAs += 1
            continue
        
        elif searchABC == 1:
            followingAs += 1
            continue
        
        else: #searchABC == 2:
            searchABC = 1
            followingAs = 1
            continue
    
    elif last == B:
        if searchABC == 0:
            continue

        elif searchABC == 1:
            searchABC += 1
            continue

        else: # searchABC == 2:
            searchABC = 0
            followingAs = 0
            continue

    else: # last == C

        if searchABC == 0:
            continue

        elif searchABC == 1:
            followingAs = 0
            searchABC = 0
            continue

        else:
            ans += followingAs
            S += ['A' for _ in range(followingAs)]
            followingAs = 0
            searchABC = 0
            continue

print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = str(input())
ans = 0
check = s.count("ABC")
while check > 0:
  ans += check
  s = s.replace("ABC","BCA")
  check = s.count("ABC")
print(ans)

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]=="A" and s[i+1]=="B" and s[i+2]=="C":
		s=s[:i]+"B"+s[i+1:]
		s=s[:i+1]+"C"+s[i+2:]
		s=s[:i+2]+"A"+s[i+3:]
		c+=1
		if i>0:
			i-=1
			flag+=1
		continue
	else:
		if flag:
			i+=2+flag
			flag=0
		else: i+=1

print(c)

Submission status: Time Limit Exceeded

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

ans = 0
bc_score = 0
flag = 1

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

while len(S) != 0:
    if S[0]=="C" and S[1] == "B":
        bc_score = 0
        bc_score += 1
        S.pop(0)
        S.pop(0)
        flag = 1
        while flag == 1 and len(S) != 0:
            flag = 0
            if S[0]=="C" and S[1] == "B":
                bc_score += 1
                S.pop(0)
                S.pop(0)
                flag = 1
            if S[0] == "A":
                ans += bc_score
                S.pop(0)
                flag = 1
    else:
        S.pop(0)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = list(input())
counter = 0
answer = 0
i = 0
while i < len(s):
  if s[i] == "A":
    counter = 1
  elif s[i] == "B":
    if counter == 1:
      counter = 2
    else:
      counter = 0
  else: # i == C
    if counter == 2:
      s[i-2] = "B"
      s[i-1] = "C"
      s[i] = "A"
      answer += 1
      i -= 4
    counter = 0
  i = i+1 if i >= 0 else 0
print(answer)

Submission status: Time Limit Exceeded

Solution code:
s=input()
ans=0
while s.count('ABC')>0:
    ans+=s.count('ABC')
    s=s.replace('ABC','BCA')
print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = list(str(input()))

ans = 0
flag=1
while(flag==1):
    flag=0
    for i in range(len(s)-2):
        if s[i] == "A" and s[i+1] == "B" and s[i+2] == "C":
            s[i] = "B"
            s[i+1] = "C"
            s[i+2] = "A"
            ans = ans+1
            flag=1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
s =  ['Z'] + list(input())

ret = 0
i = 0

while i < len(s) :
    if s[i:i+3] == ['A', 'B', 'C'] :
        s[i:i+3] = ['B', 'C', 'A']
        ret += 1
        i -= 1
    else :
        i += 1

print(ret)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

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


def choose_abc_range(s):
    ranges = []
    cur = 0
    while cur < len(s):
        if s[cur:cur+3] == "ABC":
            st = cur
            j = cur

            while s[j:j+3] == "ABC":
                j += 3

            ed = j

            ranges.append([st, ed])
            cur = j

        else:
            cur += 1

    return ranges

def get_a(sa):
    a = 0
    for sai in sa:
        if sai == "A":
            a += 1
        else:
            break

    return a

def get_bc(sb):
    b = 0
    for sbi in sb[::2]:
        if sbi == "bc":
            b += 1
        else:
            break

    return b

s = ns()
ans = 0
while "ABC" in s:

    ranges = choose_abc_range(s)
    for l, r in ranges:
        k = (r-l+1)//3

        ans += k*(k+1)//2

        s = s[:l] + "BC"*k + "A"*k + s[r:]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = input()
cnt = 0
while s.find("ABC")>-1:
    cnt += s.count("ABC")
    s = s.replace("ABC","BCA")
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
s=input()
t=len(s)
S=[0]*t
for i in range(t):
  if s[i]=='A':
    S[i]=1
  if s[i]=='B':
    S[i]=2
  if s[i]=='C':
    S[i]=3
#print(S)
ct=0
pp=1
def check(S,ct,pp):
    pp=0
    for i in range(t-2):
        if S[i]==1:
            if S[i+1]==2:
                if S[i+2]==3:
                    S[i]=2
                    S[i+1]=3
                    S[i+2]=1
                    ct+=1
                    pp=1
    return ct,pp
for i in range(20000):
    ct, pp = check(S,ct,pp)
    if pp==0:
        break
print(ct)

Submission status: Time Limit Exceeded

Solution code:
s=input()
cnt=0
abc=s.count("ABC")

while abc!=0:
    cnt+=abc
    s=s.replace("ABC","BCA")
    abc=s.count("ABC")

print(cnt)

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)
    for i in range(len(S3)):
        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:
def search(s):
    global t
    idx = -1
    ls = []
    while True:
        idx = s.find(t, idx+1)
        if idx == -1:
            break
        ls.append(idx)
    return ls


def change(s, n):
    global cnt
    cnt += 1
    tmp = list(s)
    tmp[n] = 'B'
    tmp[n+1] = 'C'
    tmp[n+2] = 'A'
    return ''.join(tmp)


def loop(s):
    global cnt
    global max_cnt
    ls = search(s)
    while True:
        if not ls:
            #print(cnt, max_cnt)
            if max_cnt < cnt:
                max_cnt = cnt
            cnt = 0
            break
        tmp = change(s, ls.pop())
        #print(tmp)
        loop(tmp)


s = input()
t = 'ABC'
cnt = 0
max_cnt = 0
if s.find(t) == -1:
    print(cnt)
    exit()
else:
    loop(s)
    print(max_cnt)

Submission status: Time Limit Exceeded

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

def Find_and_Replace(S):
    i = 2
    count = 0
    while i < len(S):
        if S[i] == 'C':
            if S[i-2] == 'A' and S[i-1] == 'B':
                S[i-2] = 'B'
                S[i-1] = 'C'
                S[i] = 'A'
                count += 1
                i += 2
            else:
                i += 3
        else:
            if S[i] == 'B':
                i += 1
            elif S[i] == 'A':
                i += 2
            else:
                i += 3
    return count
    
S = list(input())

total_count = 0
while True:
    count = Find_and_Replace(S)
    if count <= 0:
        break
    else:
        total_count += count

print(total_count)

Submission status: Time Limit Exceeded

Solution code:
S = input()

ans = 0
while S:
    now = S.find("ABC")
    if now == -1:
        break

    num_A = 1
    num_BC = 1
    S1 = S[:now]
    while len(S1) > 0 and S1[-1] == "A":
        num_A += 1
        S1 = S1[:-1]

    S2 = S[now+3:]
    while len(S2) > 0 and S2[0:2] == "BC":
        num_BC += 1
        S2 = S2[2:]

    ans += num_A*num_BC
    S = "A" + S[(now + 2 * num_BC + 1):]

print(ans)

Submission status: Time Limit Exceeded

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

import sys

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

S=list(input())
N=len(S)

def rec(cur):
    global cnt
    if cur+2<N:
        if S[cur]=='A' and S[cur+1]=='B' and S[cur+2]=='C':
            S[cur]='B'
            S[cur+1]='C'
            S[cur+2]='A'
            cnt+=1
            rec(cur+2)
i=N-1
cnt=0
while i>=0:
    if i-2>=0:
        if S[i-2]=='A' and S[i-1]=='B' and S[i]=='C':
            S[i-2]='B'
            S[i-1]='C'
            S[i]='A'
            cnt+=1
            rec(i)
    i-=1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
s = list(input())

#TLE版

ans = 0
tmp = 1
while 1:
    if tmp != 1:
        break
    tmp = 0
    for i in range(len(s)):
        if i >= len(s) - 2:
            continue
        if s[i] == 'A' and s[i+1] == 'B' and s[i+2] == 'C':
            if i - 1 > 0 and s[i-1] == 'A':
                s[i-1] = 'B'
                s[i] = 'C'
                s[i+1] = 'A'
                s[i+2] = 'A'
                tmp = 1
                ans += 2
            else:
                s[i] = 'B'
                s[i+1] = 'C'
                s[i+2] = 'A'
                tmp = 1
                ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import re


scan = sys.stdin.readline


def main():
    s = scan().rstrip() # type: str
    count = 0

    while s.find("ABC") > -1:
        if s.find("AABCBC") > -1:
            s = s.replace("AABCBC", "BCBCAAA", 1)
            count += 4
        elif s.find("AABC") > -1:
            s = s.replace("AABC", "BCAA", 1)
            count += 2
        elif s.find("ABCBC") > -1:
            s = s.replace("ABCBC", "BCBCA", 1)
            count += 2
        elif s.find("ABC") > -1:
            s = s.replace("ABC", "BCA", 1)
            count += 1

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import re

s = str(input())
count = 0
while True:
    s_n = re.sub(r"ABC", "BCA", s)
    l_find = len(re.findall(r"ABC", s))
    count += l_find

    if l_find == 0:
        print(count)
        break
    else:
        s = s_n

Submission status: Time Limit Exceeded

Solution code:

s=input()


target = 'ABC'
index = -1
count=0
debug=0
while True:
    n=s.count("ABC")
    if n==0:
        break
    count+=n
    s=s.replace("ABC","BCA",n)
    #debug+=1
    #if debug>10:
    #    break
print(count)

Submission status: Time Limit Exceeded

Solution code:
S = [ord(c) for c in list(input())]
length = len(S)

count = 0
i = 0
if length > 2:
    # i == 0
    if S[i] == 65 and S[i + 1] == 66 and S[i + 2] == 67:
        S[i] = 66
        S[i + 1] = 67
        S[i + 2] = 65
        count += 1
    # i > 0
    while i < length - 2:
        if S[i] == 65:
            if S[i + 1] == 66:
                if S[i + 2] == 67:
                    S[i] = 66
                    S[i + 1] = 67
                    S[i + 2] = 65
                    count += 1
                    if S[i - 1] == 65:
                        i -= 1
                    else:
                        i += 1
                else:
                    i += 2
            else:
                i += 1
        else:
            i += 1
print(count)

Submission status: Time Limit Exceeded

Solution code:
import sys
import re
sys.setrecursionlimit(10 ** 7)


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def SI(): return input()


def main():
    S = SI()
    ans = 0
    while(1):
        a = S.find("ABC")
        if a == -1:
            break
        ans += 1
        i = 1
        aa = 0
        while(S[a-i] == 'A' and a-i >= 0):
            ans += 1
            i += 1
            aa += 1
        S = S[a+3:]
        bc = 0
        while(S[:2] == "BC"):
            ans += 1
            S = S[2:]
            bc += 1
        ans += aa*bc
        S = "A"*(aa+1) + S
    print(ans)


main()

Submission status: Time Limit Exceeded

Solution code:
import re
base_str = input()
exp = "(A+)((BC)+)"
flg = True
res = 0
while(flg):
  tmp_res = res
  min_pos = 10000000
  max_pos = 0
  for m in re.finditer(exp, base_str):
    if min_pos > m.start(0):
      min_pos = m.start(0)
    if max_pos < m.end(0):
      max_pos = m.end(0)
    match_str = m.group(0)
    trans_num = len(m.group(1)) * len(m.group(2)) / 2
    res += int(trans_num)
    replace_str = "BC" * int(len(m.group(2)) / 2) + "A" * len(m.group(1))
    base_str = base_str[:m.start(0)] + replace_str + base_str[m.end(0):]
  base_str = base_str[min_pos:max_pos+1]
  flg = res != tmp_res
print(res)

Submission status: Time Limit Exceeded

Solution code:
s = input()

count = 0

while True:
    if 'ABC' in s:
        s = s.replace('ABC', 'BCA', 1)
#        print(s)
        count += 1
    else:
        break

print(count)

Submission status: Time Limit Exceeded

Solution code:
s = list(map(str, input()))
l = len(s)

num = 0
first = False
while True:
  flag = False
  for i in range(l-2):
    if s[i:i+3] == ["A", "B", "C"]:
      num += 1
      s[i:i+3] = ["B", "C", "A"]
      flag = True
#      break
  
  if flag == True:
    continue
  elif flag == False and first == False:
    first = True
  elif flag == False and first == True:
    break
  
print(num)

Submission status: Time Limit Exceeded

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


def solve(s: str):
    n = len(s)
    ret = 0
    i = 0
    ##while i < n - 2:
    ##    ##if s[i:i + 6] == 'ABCABC':
    ##    ##    ret += 1
    ##    if s[i:i + 3] == 'ABC':
    ##        ret += 1
    ##        s[i] = 'B'
    ##        s[i + 1] = 'C'
    ##        s[i + 2] = 'A'
    ##        #s = s[:i] + 'BCA' + s[i + 3:]

    ##        j = 1
    ##        while s[i - j:i + 3 - j] == 'ABC':
    ##            ret += 1
    ##            #s = s[:i - j] + 'BCA' + s[i + 3 - j:]
    ##            s[i - j] = 'B'
    ##            s[i + 1 - j] = 'C'
    ##            s[i + 2 - j] = 'A'
    ##            j += 1

    ##        i += 1
    ##        #while s[i:i + 2] == 'BC':
    ##        #    ret += 1
    ##        #    s = s[:i - j] + 'BCA' + s[i + 2:]
    ##        #    i += 2
    ##    else:
    ##        i += 1

    #while True:
    #    found = False
    #    i = 0
    #    tmp = []
    #    while i < n - 2:
    #        if s[i:i + 3] == 'ABC':
    #            ret += 1
    #            i += 3
    #            tmp.append('BCA')
    #            found = True
    #            #s = s[:i] + 'BCA' + s[i + 3:]
    #        else:
    #            tmp.append(s[i])
    #            i += 1
    #    if not found:
    #        break
    #    s = ''.join(tmp)

    while True:
        found = False
        i = 0
        while i < n - 2:
            if s[i:i + 3] == 'ABC':
                found = True
                ret += 1
                s = s[:i] + 'BCA' + s[i + 3:]
            i += 1

        i = n - 3
        while i >= 0:
            if s[i:i + 3] == 'ABC':
                found = True
                ret += 1
                s = s[:i] + 'BCA' + s[i + 3:]
            i -= 1

        if not found:
            break

    print(ret)
    return


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:
import re
s = input()
l = list(map(str, s))
c = 0

while re.search('ABC', ''.join(l)) :
    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']
    
print(c)

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]=="A" and s[i+1]=="B" and s[i+2]=="C":
		s=s[:i]+"B"+s[i+1:]
		s=s[:i+1]+"C"+s[i+2:]
		s=s[:i+2]+"A"+s[i+3:]
		c+=1
		if i>0:
			i-=1
			flag=1
		continue
	else:
		if flag:
			i+=3
			flag=0
		else: i+=1

print(c)

Submission status: Time Limit Exceeded

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



S = list("Z"+str(input()))
idx = 1
l = len(S)

ans = 0
while(idx <= l-3):
  if S[idx]+S[idx+1]+S[idx+2] == "ABC":
    ans += 1
    S[idx],S[idx+1],S[idx+2] = ["B","C","A"]
    idx -= 1
  else:
    idx += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

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


def choose_abc_range(s):
    ranges = []
    cur = 0
    while cur < len(s):
        if s[cur:cur+3] == "ABC":
            st = cur
            j = cur

            while s[j:j+3] == "ABC":
                j += 3

            ed = j

            ranges.append([st, ed])
            cur = j

        else:
            cur += 1

    return ranges

def get_a(sa):
    a = 0
    for sai in sa:
        if sai == "A":
            a += 1
        else:
            break

    return a

def get_bc(sb):
    b = 0
    for sbi in sb[::2]:
        if sbi == "bc":
            b += 1
        else:
            break

    return b

s = ns()
ans = 0
while "ABC" in s:

    ranges = choose_abc_range(s)

    for l, r in ranges:
        k = (r-l+1)//3

        ans += k

        s = s[:l] + "BCA"*k + s[r:]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = input()
L = len(s)
s = s + "hh"
count = 0
new_count = 1
LIST = range(L,1,-1)
while(new_count):
    new_list = []
    new_count = 0
    for i in LIST:
        if s[i] == "C":
            if s[i-1] == "B":
                if s[i-2] == "A":
                    new_list.append(i+2)
                    new_list.append(i-1)
                    s = s[:i-2] + "BCA" + s[i+1:]
                    new_count += 1
    count += new_count
    LIST = [i for i in new_list]
print(count)

Submission status: Time Limit Exceeded

Solution code:
s = list(map(str, input()))
l = len(s)

num = 0
first = False
while True:
  flag = False
  for i in range(l-2):
    if s[i:i+3] == ["A", "B", "C"]:
      num += 1
      s[i:i+3] = ["B", "C", "A"]
      flag = True
      break
  
  if flag == True:
    continue
  elif flag == False and first == False:
    first = True
  elif flag == False and first == True:
    break
  
print(num)

Submission status: Time Limit Exceeded

Solution code:
s = input()
k = 0
kk = 0
ans = 0
while True:
    
    if k >= len(s) - 1:
        break
    if s[k : k + 3] == "ABC":
        s = s[:k] + "BCA" + s[k+3:]
        kk = k
        k -= 1
        ans += 1
    else:
        k += 1
        if kk > k:
            k = kk

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=0
txt=raw_input()
txt_c=txt.replace("ABC","BCA",1)

while txt_c!=txt:
  txt_c=txt.replace("ABC","BCA",1)
  txt=txt_c
  txt_c=txt.replace("ABC","BCA",1)
  n=n+1
else:
  print n

Submission status: Time Limit Exceeded

Solution code:
s=input()
cnt=0

while s.count("ABC")!=0:
    for i in range(s.count("ABC")):
        s=s.replace("ABC","BCA",1)
        cnt+=1

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
s=input()


i=0
c=0
while True:
	if i>len(s)-3: break
	if s[i]=="A" and s[i+1]=="B" and s[i+2]=="C":
		s=s[:i]+"B"+s[i+1:]
		s=s[:i+1]+"C"+s[i+2:]
		s=s[:i+2]+"A"+s[i+3:]
		c+=1
		if i>0: i-=1
		continue
	else: i+=1

print(c)

Submission status: Time Limit Exceeded

Solution code:
s=list(input())
n=len(s)
i,a=0,0
for i in range(n-2):
  if s[i]+s[i+1]+s[i+2]=="ABC":
    s[i],s[i+1],s[i+2]="B","C","A"
    a+=1
    j=1
    while i-j>-1and s[i-j]=="A":
      s[i-j],s[i-j+1],s[i-j+2]="B","C","A"
      a+=1;j+=1
print(a)

Submission status: Time Limit Exceeded

Solution code:
S=list(input())
l = len(S)
i = 0
j = -1
ans = 0
while i<l:
    if j==-1 and S[i] == "A":
        j=i
        i+=1
    elif j>=0 and S[i] == "A":
        i+=1
    elif j>=0:
        if len(S[i:i+2])==2 and S[i] == "B" and S[i+1] == "C":
            S[i] = "A"
            S[i+1] = "A"
            S[j] = "B"
            S[j+1] = "C"
            ans += i-j
            i = j
            j = -1
        else:
            j = -1
            i+=1
    else:
        i+=1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import re

s =  input()

ret = 0
t = re.subn('ABC', 'BCA', s)

while t[1] :
    ret += t[1]
    t = re.subn('ABC', 'BCA', t[0])

print(ret)

Submission status: Time Limit Exceeded

Solution code:
A = input() 
found = False
count = 0
while not found:
    C = A.replace("ABC","BCA",1)
    if C == A:
        found = True
    else:
        count += 1
        A = C
print(count)

Submission status: Time Limit Exceeded

Solution code:
s = list(input())
c = 0
state = 0
res = 0
while c < len(s):
    #print("c" + str(c))
    #print("cur: " + "".join(s))
    #print("state" + str(state))
    if state == 0:
        if s[c] == "A":
            state = 1
    elif state == 1:
        if s[c] == "B":
            state = 2
        else:
            state = 0
            if s[c] == "A":
                state = 1
    elif state == 2:
        if s[c] == "C":
            #print("hit")
            res += 1
            s[c-2], s[c-1], s[c] = "B", "C", "A"
            c = c - 3
            state = 0
        else:
            state = 0
        if s[c] == "A":
            state = 1
    c = c + 1
print(res)

Submission status: Time Limit Exceeded

Solution code:

s=input()


target = 'ABC'
index = -1
count=0
while True:

    if "ABC" not in s:
        break
    count+=1
    s=s.replace("ABC","BCA",1)
print(count)