Problem:


Score : 400 points

Problem Statement

We have a string S of length N consisting of R, G, and B.

Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:

S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.

j - i \neq k - j.

Constraints

1 \leq N \leq 4000

S is a string of length N consisting of R, G, and B.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of triplets in question.

Sample Input 1

4
RRGB

Sample Output 1

1

Only the triplet (1,~3,~4) satisfies both conditions. The triplet (2,~3,~4) satisfies the first condition but not the second, so it does not count.

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800



Sample input:
4
RRGB


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappop, heappush

from decimal import *

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

##### 累乗 #####
# pow(x, y, z) -> x**y % z

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	N = inputInt()
	S = input()
	S = S[:-1]

	R = []
	G = []
	B = []
	for i,val in enumerate(S):
		if val == "R":
			R.append(i)
		elif val == "G":
			G.append(i)
		else:
			B.append(i)

	ans = 0
	for i,val in enumerate(R):
		tmp = bisect_right(G, val)
		if len(G) == tmp:
			break

		for j in range(tmp,len(G)):
			tmptmp = bisect_right(B, G[j])
			if len(B) == tmptmp:
				break

			for k in range(tmptmp,len(B)):
				if G[j] - val == B[k] - G[j]:
					pass
				else:
					ans += 1

	for i,val in enumerate(R):
		tmp = bisect_right(B, val)
		if len(B) == tmp:
			break

		for j in range(tmp,len(B)):
			tmptmp = bisect_right(G, B[j])
			if len(G) == tmptmp:
				break

			for k in range(tmptmp,len(G)):
				if B[j] - val == G[k] - B[j]:
					pass
				else:
					ans += 1

	for i,val in enumerate(B):
		tmp = bisect_right(G, val)
		if len(G) == tmp:
			break

		for j in range(tmp,len(G)):
			tmptmp = bisect_right(R, G[j])
			if len(R) == tmptmp:
				break

			for k in range(tmptmp,len(R)):
				if G[j] - val == R[k] - G[j]:
					pass
				else:
					ans += 1

	for i,val in enumerate(B):
		tmp = bisect_right(R, val)
		if len(R) == tmp:
			break

		for j in range(tmp,len(R)):
			tmptmp = bisect_right(G, R[j])
			if len(G) == tmptmp:
				break

			for k in range(tmptmp,len(G)):
				if R[j] - val == G[k] - R[j]:
					pass
				else:
					ans += 1

	for i,val in enumerate(G):
		tmp = bisect_right(B, val)
		if len(B) == tmp:
			break

		for j in range(tmp,len(B)):
			tmptmp = bisect_right(R, B[j])
			if len(R) == tmptmp:
				break

			for k in range(tmptmp,len(R)):
				if B[j] - val == R[k] - B[j]:
					pass
				else:
					ans += 1

	for i,val in enumerate(G):
		tmp = bisect_right(R, val)
		if len(R) == tmp:
			break

		for j in range(tmp,len(R)):
			tmptmp = bisect_right(B, R[j])
			if len(B) == tmptmp:
				break

			for k in range(tmptmp,len(B)):
				if R[j] - val == B[k] - R[j]:
					pass
				else:
					ans += 1

	print(ans)

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# special thanks :
#  https://nagiss.hateblo.jp/entry/2019/07/01/185421
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]

def int_sqrt2(n):
    def f(prev):
        while True:
            m = (prev + n / prev) / 2
            if m >= prev:
                return prev
            prev = m

    return f(int(math.sqrt(n) * (1 + 1e-10)))

# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
	# comb = Combination(n+r-1, mod)
	# return comb(n+r-1, r)
    return combination(n+r-1, r, mod)

class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = str(input())

sum = 0

for i in range(1,N-1):
	for j in range(i+1,N):
		if S[i-1]==S[j-1]:
			continue
		for k in range(j+1,N+1):
			if (j-i)==(k-j):
				pass
			else:
				if S[i-1]!=S[k-1] and S[j-1]!=S[k-1]:
					sum+=1
print(sum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()

R = [0] * N
G = [0] * N
B = [0] * N

for i in range(1, N):
    if S[-i] == "R":
        R[-i] += R[-i + 1] + 1 if i != 1 else 1
        G[-i] += G[-i + 1]
        B[-i] += B[-i + 1]
    if S[-i] == "G":
        R[-i] += R[-i + 1]
        G[-i] += G[-i + 1] + 1 if i != 1 else 1
        B[-i] += B[-i + 1]
    if S[-i] == "B":
        R[-i] += R[-i + 1]
        G[-i] += G[-i + 1]
        B[-i] += B[-i + 1] + 1 if i != 1 else 1

ans = 0
for i in range(N):
    for j in range(i + 1, N):
        k = j + 1
        if k >= N:
            break
        if S[i] == S[j]:
            continue
        if not ("R" in S[i] + S[j]):
            ans += R[k]
            if R[k] > 0 and (2 * j - i) < N and S[2 * j - i] == "R":
                ans -= 1
        elif not ("G" in S[i] + S[j]):
            ans += G[k]
            if G[k] > 0 and (2 * j - i) < N and S[2 * j - i] == "G":
                ans -= 1
        else:
            ans += B[k]
            if B[k] > 0 and (2 * j - i) < N and S[2 * j - i] == "B":
                ans -= 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

n = int(stdin.readline().rstrip())
data = list(stdin.readline().rstrip().split()[0])

count = 0

for i in range(n):
    s_1 = data[i]
    for j in range(i+1, n):
        if s_1 != data[j]:
            s_2 = data[j]
            for k in range(j+1, n):
                s_3 = data[k]
                if s_1 != s_3 and s_2 != s_3:
                    if (k - j) != (j - i):
                        count += 1

print(count)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=list(input())
rlist=[]
glist=[]
blist=[]
ans=0
if len(s)<=3:
    print(0)
    exit()
for i in range(n):
    if s[i]=="R":
        rlist.append(i)
    elif s[i]=="G":
        glist.append(i)
    else:
        blist.append(i)
if len(rlist)==0 or len(glist)==0 or len(blist)==0:
    print(0)
    exit()
for i in rlist:
    for j in glist:
        for k in blist:
            tmp1=max(i,j,k)
            tmp2=min(i,j,k)
            tmp3=i+j+k-tmp1-tmp2
            if tmp2-tmp3 != tmp3-tmp1:
                ans+=1
            else:
                continue
print(ans)

Submission status: Time Limit Exceeded

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

count = 0
 
for i,first in enumerate(s[:-2]):
    r_count = s[i+1:].count('R')
    g_count = s[i+1:].count('G')
    b_count = s[i+1:].count('B')
    for j,second in enumerate(s[i+1:n-1]):
        if second == 'R':
            r_count -=1
        elif second == 'G':
            g_count -=1
        else:
            b_count -=1
        if first != second:
            if 'R' != first and 'R' != second:
                count += r_count
                third = 'R'
            elif 'G' != first and 'G' != second:
                count += g_count
                third = 'G'
            else:
                count += b_count
                third = 'B'
            if i+j+2+j <= n-1 and s[i+j+2:][j] == third:
                count -= 1

 
print(count)

Submission status: Time Limit Exceeded

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


def solve(N: int, S: str):
    count = 0
    for i in range(N):
        if S[i] == "R":
            for j in range(i + 1, N):
                if S[j] == "G":
                    for k in range(j + 1, N):
                        if S[k] == "B" and j - i != k - j:
                            count += 1
                elif S[j] == "B":
                    for k in range(j + 1, N):
                        if S[k] == "G" and j - i != k - j:
                            count += 1
        elif S[i] == "G":
            for j in range(i + 1, N):
                if S[j] == "R":
                    for k in range(j + 1, N):
                        if S[k] == "B" and j - i != k - j:
                            count += 1
                elif S[j] == "B":
                    for k in range(j + 1, N):
                        if S[k] == "R" and j - i != k - j:
                            count += 1
        else:
            for j in range(i + 1, N):
                if S[j] == "G":
                    for k in range(j + 1, N):
                        if S[k] == "R" and j - i != k - j:
                            count += 1
                elif S[j] == "R":
                    for k in range(j + 1, N):
                        if S[k] == "G" and j - i != k - j:
                            count += 1

    print(count)
    return


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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import itertools

def solve():
    N = int(input())
    S = input()
    d = {"R": [], "G": [], "B": []}
        
    for i, s in enumerate(S):
        d[s].append(i)

    def rec():
        ans = 0
        for a, b, c in list(itertools.product(d["R"], d["G"], d["B"])):
            if c-b >0 and b-a>0 and c-b != b-a: ans += 1
            if b-c >0 and c-a>0 and b-c != c-a: ans += 1
            if c-a >0 and a-b>0 and c-a != a-b: ans += 1
            if a-c >0 and c-b>0 and a-c != c-b: ans += 1
            if b-a >0 and a-c>0 and b-a != a-c: ans += 1
            if a-b >0 and b-c>0 and a-b != b-c: ans += 1

        return ans
        
    return rec()

print(solve())

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = list(input())
ans = 0
for i in range(N):
    for j in range(i+1,N):
        if S[i] != S[j]:
            for k in range(j+1,N):
                if j-i != k-j and S[j] != S[k] and S[i] != S[k]:
                    ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
S=input()
r=[1 if S[0]=="R" else 0]
g=[1 if S[0]=="G" else 0]
b=[1 if S[0]=="B" else 0]

for i in range(1,N):
  if S[i]=="R":
    r.append(r[-1]+1)
    g.append(g[-1])
    b.append(b[-1])
  elif S[i]=="G":
    r.append(r[-1])
    g.append(g[-1]+1)
    b.append(b[-1])
  else:
    r.append(r[-1])
    g.append(g[-1])
    b.append(b[-1]+1)

#print(r)
#print(g)
#print(b)

st={"R","G","B"}

def calc(i,j):
  tmp={i,j}
  ans=st-tmp
  return ans.pop()

#print(calc("R","G"))
ans=0

for i in range(0,N-2):
  for j in range(i+1,N-1):
    if S[j]==S[i]:
      pass
    else:            
      tmp=calc(S[i],S[j])
      if tmp=="R":
        #print(i,j,tmp,r[-1],r[j])
        ans += r[-1]-r[j]
        if j+(j-i)<=N-1:
          if S[j+(j-i)]==tmp:
            ans -=1
      elif tmp=="G":
        #print(i,j,tmp,g[-1],g[j])
        ans += g[-1]-g[j]
        if j+(j-i)<=N-1:
          if S[j+(j-i)]==tmp:
            ans -=1
      else:
        #print(i,j,tmp,b[-1],b[j])
        ans += b[-1]-b[j]
        if j+(j-i)<=N-1:
          if S[j+(j-i)]==tmp:
            ans -=1

print(ans)

Submission status: Time Limit Exceeded

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

import sys
import math

debug = False

def log(text):
    if debug:
        print(text)


def parse_input(lines_as_string = None):

    global debug
    lines = []
    if lines_as_string is None:
        debug = False
        # for line in sys.stdin:
        #     lines.append(line)
        lines.append(input())
        lines.append(input())
    else:
        debug = True
        lines = [e for e in lines_as_string.split("\n")][1:-1]
    
    n = int(lines[0])
    s = lines[1]

    return (n, s)


def solve(n, s):

    result = sum([ 1 for i in range(n-2) for j in range(i+1, n-1) for k in range(j+1, n)
      if s[i] != s[j] and s[i] != s[k] and s[j] != s[k] and j - i != k - j])
    
    return result

def main():
    # 出力
    result = solve(*parse_input())
    if isinstance(result, list):
        for r in result:
            print("%s" % r, sep='')
    else:
        print("%s" % result, sep='')

if __name__ == '__main__':

    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
printV = lambda x: print(*x, sep="\n")
printH = lambda x: print(" ".join(map(str,x)))
def IS(): return sys.stdin.readline()[:-1]
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LII(rows_number): return [II() for _ in range(rows_number)]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]

def main():
	n = II()
	s = IS()
	r,g,b=[],[],[]

	def binary_search(lst, K):
		l = 0; r = len(lst);
		while(l+1<r):
			mid = (l+r)//2
	    #下記の操作を書き換えることによって探索条件を変更可能
			if(lst[mid]>K): r=mid
			else: l=mid
		return l

	for i,ss in enumerate(s):
		if ss=='R':
			r.append(i)
		elif ss=='G':
			g.append(i)
		else:
			b.append(i)
	ans=len(r)*len(g)*len(b)
	for rr in r:
		for gg in g:
			a=max(rr,gg)+abs(rr-gg)
			if a in b:
				ans-=1
			a=min(rr,gg)-abs(rr-gg)
			if a in b:
				ans-=1
			if((rr+gg)%2==0):
				a=(rr+gg)//2
				if a in b:
					ans-=1
	print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import math
N = int(input())
S = input()
ans = 0
for k in range(2, N):
    for j in range(1, k):
        if S[j] == S[k]:
            continue
        for i in range(j):
            if S[i] == S[j]:
                continue
            if S[i] == S[k]:
                continue
            if j-i == k-j:
                continue
            ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value

N = ii()
S = input()
h = [0]*N

for i, a in enumerate(S):
    if a=='R':
        h[i] = 0
    elif a=='G':
        h[i] = 1
    else:
        h[i] = 9

cnt = -1
ans = 0
for i in range(N):
    cnt = h[i]
    for j in range(i+1, N):
        num = cnt + h[j]
        for k in range(j+1, N):
            if num + h[k] == 10 and k!=2*j-i:
                ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()
ans = 0
for i in range(len(s)):
    one = s[i]
    for j in range(i + 1, len(s)):
        if s[j] == one:
            continue
        dis1 = j - i
        two = s[j]
        for k in range(j + 1, len(s)):
            if s[k] == one or s[k] == two:
                continue
            else:
                dis2 = k - j
                if dis1 != dis2:
                    ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
ans = 0
for i in range(N-2):
    for j in range(i+1,N-1):
        for k in range(j+1,N):
            if S[i] == S[j] or S[j] == S[k] or S[k] == S[i]:
                continue
            elif j-i == k-j:
                continue
            else:
                ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()

ans = 0
for i in range(0,N-2):
    for j in range(i+1,N-1):
        if (S[i] == S[j]):
            continue
        for k in range(j+1,N):
            if (S[i] == S[k] or S[j] == S[k]):
                continue
            elif j-i != k-j:
                ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
S=list(input())

ans=0
i=0
while i<N-2:
    j=i+1
    while j<N-1:
        k=j+1
        while k<N:
            ans+=1*(S[i]!=S[j])*(S[j]!=S[k])*(S[k]!=S[i])*(j-i!=k-j)
            k+=1
        j+=1
    i+=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()

rn = [0]*(N+1)
gn = [0]*(N+1)
bn = [0]*(N+1)

for i in range(N):
    rn[i+1] = rn[i]
    gn[i+1] = gn[i]
    bn[i+1] = bn[i]
    if S[i]=="R":
        rn[i+1] = rn[i]+1
    if S[i]=="G":
        gn[i+1] = gn[i]+1
    if S[i]=="B":
        bn[i+1] = bn[i]+1
   
ans = 0
for i in range(N):
    a = S[i]
    rem = "RGB".replace(a,"")
    for j in range(N-i):
        if (S[j+i] == a):
            continue
        b = S[j+i]
        rem2 = rem.replace(b,"")
        if rem2 == "R":
            ans += rn[N]-rn[j+i+1]
        if rem2 == "G":
            ans += gn[N]-gn[j+i+1]
        if rem2 == "B":
            ans += bn[N]-bn[j+i+1]
        if 0 <= j*2+i <= N-1:
          if S[j*2+i] == rem2 :
              ans -=1
            
print(ans)

Submission status: Time Limit Exceeded

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

def abc162d(n, s):

    r_arr = []
    g_arr = []
    b_arr = []

    for i in range(n):
        if s[i] == 'R':
            r_arr.append(i)
        elif s[i] == 'G':
            g_arr.append(i)
        else: # 'B'
            b_arr.append(i)

    ans = 0
    for r_i in r_arr:
        for g_i in g_arr:
            for b_i in b_arr:
                tgt_list = [r_i, g_i, b_i]
                tgt_list.sort()

                if tgt_list[1] - tgt_list[0] != tgt_list[2] - tgt_list[1]:
                    ans += 1
    return ans

###
# main
if(__name__ == '__main__'):
    # input
    n = int(input())
    s = input()
    
    ans = abc162d(n, s)
    
    # output
    print(ans)
# else:
    # do nothing

Submission status: Time Limit Exceeded

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

ans = 0

for i in range(0,n-2):
    for j in range(i+1,n-1):
        for k in range(j+1,n):
            if(s[i] != s[j] and s[j] != s[k] and s[k]!=s[i] and j-i!=k-j):
                ans+=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input().strip())
S = input().strip()

csum = {
  'R': [0]*(N+1),
  'G': [0]*(N+1),
  'B': [0]*(N+1)
}
for i, c in enumerate(S):
  for k in csum.keys():
    csum[k][i+1] = csum[k][i]
  csum[c][i+1] += 1

ans = 0
for j in range(1, N-1):
  for i in range(j):
    if S[i] == S[j]: continue
    s = set('RGB') - {S[i], S[j]}
    s = s.pop()
    diff = j-i
    cand = csum[s][-1] - csum[s][j]
    if j+diff < N and S[j+diff] == s: cand -= 1
    ans += cand
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N =int(input())
S = str(input())
A = 0
R = []
G = []
B = []
for i in range(len(S)):
  if S[i] == "R":
    R.append(i+1)
  elif S[i] == "G":
    G.append(i+1)
  else:
    B.append(i+1)
#print(R)
#print(G)
#print(B)

for r in R:
  for g in G:
    for b in B:
      C = sorted([r,g,b])
      if C[1] - C[0] != C[2] - C[1]:
        A += 1
print(A)

Submission status: Time Limit Exceeded

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

ans = 0
for i in range(n-2):
    one = s[i]
    for j in range(i+1,n-1):
        if one == s[j]:
            continue
        two = s[j]
        l = j-i
        for k in range(j+1,n):
            if s[k] != one and s[k] != two:
                if k-j != l:
                    ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#from operator import itemgetter
#from collections import Counter
#import heapq
N = int(input())
S = input()
#N, M = map(int, input().split())
#A = list(map(lambda x: int(x)*(-1), input().split()))
#A = [int(input()) for i in range(N)]
#C = [list(map(int, input().split())) for i in range()]
R  =[]
G  =[]
B  =[]
answer = 0
for i, s in enumerate(S):
    if s == 'R':
        R.append(i)
    elif s == 'G':
        G.append(i)
    else:
        B.append(i)
l_B = len(B) 
for r in R:
    for g in G:
        sa = abs(r-g)
        hiku = 0
        for b in B:
            if sa == abs(b-r) or sa == abs(b-g) or abs(b-r) == abs(g-b):
                hiku += 1

        answer += l_B - hiku

print(answer)

Submission status: Time Limit Exceeded

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

r = s.count("R")
g = s.count("G")
b = s.count("B")

ans = r * g * b

c = {"R", "G", "B"}

for i in range(n):
    for j in range(i + 1, n):
        if j - i + j < n:
            if {s[i], s[j], s[j - i + j]} == c:
                ans -= 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
S=input()
ans=0
R=[]
G=[]
B=[]
for i,s in enumerate(S):
  if s=="R":
    R.append(i)
  elif s=="G":
    G.append(i)
  else:
    B.append(i)

for r in R:
  for g in G:
    for b in B:
      i=min(min(r,g),b)
      k=max(max(r,g),b)
      if r!=i and r!=k:
        j=r
      elif g!=i and g!=k:
        j=g
      else:
        j=b
      
      if j-i!=k-j:
        ans+=1
print(ans)

Submission status: Time Limit Exceeded

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

count = 0

r_index = []
g_index = []
b_index = []
for idx in range(n):
    if s[idx] == "R":
        r_index.append(idx+1)
    elif s[idx] == "G":
        g_index.append(idx+1)
    else:
        b_index.append(idx+1)

for r_idx in r_index:
    for g_idx in g_index:
        for b_idx in b_index:
          num_list = [r_idx, g_idx, b_idx]
          num_list = sorted(num_list)
          i, j, k = map(int, num_list)
          if (j-i) != (k-j):
              count += 1  

# for i in range(n):
    # for j in range(i+1, n):
        # for k in range(j+1, n):
            # if (j - i) != (k - j): 
                # if s[i] != s[j] and s[i] != s[k] and s[j] != s[k]:
                    # count += 1
                    # print(i, j, k)

print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()
ans = 0

for i in range(n):
    si = s[i]
    for j in range(i+1, n):
        sj = s[j]
        if si == sj:
            continue
        else:
            for k in range(j+1, n):
                sk = s[k]
                if j - i != k - j and sj != sk and sk != si:
                    ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math

N=int(input())
S=input()

R=[]
G=[]
B=[]

for i in range(N):
    if S[i] == "R":
        R.append(i+1)
    elif S[i] == "G":
        G.append(i+1)
    elif S[i] == "B":
        B.append(i+1)
    
ans = 0
for i in range(len(R)):
    for j in range(len(G)):
        diff = abs(R[i]-G[j])

        ans += len(B)
        if R[i]>G[j]:
            if (R[i]+diff) in B:
                ans-=1
            if (G[j]-diff) in B:
                ans-=1
            if diff % 2 == 0 and (R[i]-(diff/2)) in B:
                ans-=1
        else:
            if (G[j]+diff) in B:
                ans-=1
            if (R[i]-diff) in B:
                ans-=1
            if diff % 2 == 0 and (G[j]-(diff/2)) in B:
                ans-=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
 
x1 = int(input())
x2 = input()
RGB = {"R", "G", "B"}
_sum = 0
for i, rgb in zip(itertools.combinations(range(x1), 3), itertools.combinations(x2, 3)):
    if set(rgb) == RGB and (i[1] - i[0]) != (i[2] - i[1]):
        _sum += 1
print(_sum)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = list(input())
ans = 0
r = []
g = []
b = []
for i in range(n):
    if s[i]=='R':r.append(i)
    elif s[i]=='G':g.append(i)
    else:b.append(i)
for i in r:
    for j in g:
        for k in b:
            x,y,z = sorted([i,j,k])
            if y-x!=z-y:
                ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = input("")
S = input("")
N = int(N)
X = 0

for i in range(N-3):
    #i = ii+1
    j = i+1
    while j < N-1:
        if S[j] != S[i]:
            k = j+1
            while k < N:
                if S[k] != S[j] and S[k] != S[i] and j-i != k-j:
                    X += 1
                k += 1
        j += 1
print(X)

Submission status: Time Limit Exceeded

Solution code:
## coding: UTF-8
from decimal import *
from itertools import permutations, combinations,combinations_with_replacement,product
import math
from math import gcd

N = int(input())
S = input()

r_list = []
g_list = []
b_list = []

for i in range(N):
    if(S[i] == 'R'):
        r_list.append(i)
    elif(S[i] == 'G'):
        g_list.append(i)
    else:
        b_list.append(i)

#print('r:{}, g:{}, b:{}'.format(r_list, g_list, b_list))

R_count = len(r_list)
G_count = len(g_list)
B_count = len(b_list)
#print(R_count * G_count * B_count)

counter = R_count * G_count * B_count
NG_list = []
for i in range(R_count):
    for j in range(G_count):
        r = r_list[i]
        g = g_list[j]
        hit_count = 0
        if( (g+g-r) in b_list):
            hit_count += 1
        if( (g+r)%2 == 0 and ((g+r)/2) in b_list ):
            hit_count+=1
        if( (r-g+r) in b_list):
            hit_count+=1
        counter -= hit_count
print(counter)

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = int(input())
    s = [ord(l) for l in input()]
    r = 0

    for k in range(n):
        for j in range(k):
            for i in range(j):
                if j - i != k - j and s[i] != s[j] and s[i] != s[k] and s[j] != s[k]:
                    r += 1
    print(r)


main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
ans = 0

for i in range(N):
    for j in range(i+1, N):
        for k in range(j+1, N):
            if j-i == k-j:
                continue
            if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
                ans += 1

print(ans)

Submission status: Time Limit Exceeded

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

ans = 0
for i in range(1, n+1):
    for j in range(i, n+1):
        for k in range(j, n+1):
            if sl[i-1] != sl[j-1] and sl[j-1] != sl[k-1] and sl[k-1] != sl[i-1]:
                if j-i != k-j:
                    ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N= int(input())
S=input()
r=[]
g=[]
b=[]
for i in range(N):
    if S[i]=="R":
        r.append(i)
    elif S[i]=="G":
        g.append(i)
    else:
        b.append(i)

t=0
for i in range(len(r)):
    for j in range(len(g)):
        p=0
        for k in range(len(b)):
            if p<3:
                if abs(r[i]-g[j])!=abs(b[k]-g[j]) and abs(r[i]-b[k])!=abs(b[k]-g[j]) and abs(r[i]-g[j])!=abs(b[k]-r[i]):
                    t=t+1
                else:
                    p+=1
            else:
                t = t + 1
print(t)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = list(input())

cnt = 0
for i in range(n):
  for j in range(i+1, n):
    if s[i] != s[j]:
      for k in range(j+1, n):
        if s[i] != s[k] and s[j] != s[k]:
          if j-i != k-j:
            cnt += 1
print(cnt)