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

			blacks = G[j] - val + G[j]
			lislis = B[tmptmp:]
			
			if blacks in lislis:
				ans += len(B)-tmptmp-1
			else:
				ans += len(B)-tmptmp

		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

			blacks = B[j] - val + B[j]
			lislis = G[tmptmp:]
			if blacks in lislis:
				ans += len(G)-tmptmp-1
			else:
				ans += len(G)-tmptmp


	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

			blacks = G[j] - val + G[j]
			lislis = R[tmptmp:]
			if blacks in lislis:
				ans += len(R)-tmptmp-1
			else:
				ans += len(R)-tmptmp

		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

			blacks = R[j] - val + R[j]
			lislis = G[tmptmp:]
			if blacks in lislis:
				ans += len(G)-tmptmp-1
			else:
				ans += len(G)-tmptmp

	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

			blacks = B[j] - val + B[j]
			lislis = R[tmptmp:]
			if blacks in lislis:
				ans += len(R)-tmptmp-1
			else:
				ans += len(R)-tmptmp

		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

			blacks = R[j] - val + R[j]
			lislis = B[tmptmp:]
			if blacks in lislis:
				ans += len(B)-tmptmp-1
			else:
				ans += len(B)-tmptmp

	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 = list(input())

i_range = [int(x) for x in range(1, N-1)]
j_range = [int(x) for x in range(2, N)]
k_range = [int(x) for x in range(3, N+1)]

val = 0

for k in k_range:
    for j in j_range:
        if(j >= k):
            break
        for i in i_range:
            if(i >= j):
                break
            if((S[i-1] != S[j-1]) and (S[j-1] != S[k-1]) and (S[i-1] != S[k-1])):
                if(j-i != k-j):
                    val = val + 1

print(val)

Submission status: Time Limit Exceeded

Solution code:
def rgb(n,s):
    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:
                    if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
                        ans += 1
    print(ans)

n = int(input())
s = input()
rgb(n, s)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

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

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


for i in range(n):
    if data[i] == "R":
        r_list.append(i)
    elif data[i] == "G":
        g_list.append(i)
    else:
        b_list.append(i)

count = len(r_list) * len(g_list) * len(b_list)

for r in r_list:
    for g in g_list:
        for b in b_list:
            if abs(r-g) == abs(g-b) or abs(r-b) == abs(g-b) or abs(r-b) == abs(r-g):
                count -= 1

print(count)

Submission status: Time Limit Exceeded

Solution code:

n = int(input())
s = input()

cnt = 0

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

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
# from math import factorial,sqrt,ceil
from itertools import permutations as permus
# from fractions import gcd
from collections import deque,Counter
import re
# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

# import numpy as np
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix

# strlist = "abcdefghijklmnopqrstuvwxyz"
N = int(input())
S = input()

Sset = Counter(S)
iter = permus(list("RGB")) 

total = Sset["R"]*Sset["G"]*Sset["B"]

Slen = len(S)
# hikukazu = 0
ans = 0
for i in range(Slen):
    for j in range(i,Slen):
        for k in range(j,Slen):
            if S[i]!=S[j] and S[i]!=S[k] and S[k]!=S[j]:
                if not j-i == k-j:
                    ans += 1

# ans = total - hikukazu
print(ans)
# print(*ans)   # unpackして出力。間にスペースが入る
# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=input()
R=[]
B=[]
G=[]
for i in range(0,n):
    if s[i]=="R":
        R.append(i)
    elif s[i]=="B":
        B.append(i)
    else:
        G.append(i)
ans=0
for i in range(0,len(R)):
    for j in range(0,len(B)):
            if R[i]>B[j]:
                if((R[i]+B[j])%2==0 and int((R[i]+B[j])/2)in G):
                    ans=ans+1
                if ((2*B[j]-R[i])in G):
                    ans=ans+1
                if ((2*R[i]-B[j])in G):
                    ans=ans+1
            else:
                if((R[i]+B[j])%2==0 and int((R[i]+B[j])/2)in G):
                    ans=ans+1
                if ((-B[j]+2*R[i])in G):
                    ans=ans+1
                if ((-R[i]+2*B[j])in G):
                    ans=ans+1
print(len(R)*len(B)*len(G)-ans)

Submission status: Time Limit Exceeded

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

num_r = S.count('R')
num_g = S.count('G')
num_b = N - num_r - num_g
C = [[num_r, num_g, num_b] for _ in range(N)]
r_cnt, g_cnt, b_cnt = 0, 0, 0

for i in range(N):
    if S[i] == 'R':
        r_cnt += 1
    elif S[i] == 'G':
        g_cnt += 1
    else:
        b_cnt += 1

    C[i][0] -= r_cnt
    C[i][1] -= g_cnt
    C[i][2] -= b_cnt

ans = 0
for i in range(N-2):
    for j in range(i+1, N-1):
        if S[i] != S[j]:
            if 'R' not in [S[i], S[j]]:
                ans += C[j][0]
                if j+(j-i) < N and S[j+(j-i)]=='R':
                    ans -= 1
            if 'G' not in [S[i], S[j]]:
                ans += C[j][1]
                if j+(j-i) < N and S[j+(j-i)]=='G':
                    ans -= 1
            if 'B' not in [S[i], S[j]]:
                ans += C[j][2]
                if j+(j-i) < N and S[j+(j-i)]=='B':
                    ans -= 1

        #print(S[i], S[j], ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
if __name__ == "__main__":
    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 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:
def main():
    from collections import Counter

    N = int(input())
    S = list(input())
    s_c = Counter(S)

    a = s_c["R"] * s_c["B"] * s_c["G"]

    for i in range(N):
        for j in range(i + 1, N):
            for _ in range(j + 1, N):
                if (S[i] != S[j] and S[i] != S[_] and S[j] != S[_]) and \
                    not (j - i != _ - j):
                    a -= 1
    print(a)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

R_list=[]
G_list=[]
B_list=[]
daburi = 0

for i in range(n):
    if s.find('R') == 0:
        R_list.append(i)
    elif s.find('G') == 0:
        G_list.append(i)
    else:
        B_list.append(i)
    s = s[1:]

for j in range(len(R_list)):
    for k in range(len(G_list)):
        for l in range(len(B_list)):
            if abs(R_list[j] - G_list[k]) == abs(G_list[k]- B_list[l]) or abs(R_list[j] - G_list[k]) == abs(R_list[j] - B_list[l]) or abs(G_list[k]- B_list[l]) == abs(R_list[j]- B_list[l]) :
                    daburi +=1

ans = len(R_list)*len(G_list)*len(B_list)
print(ans - daburi)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

N = int(input())
S = input().strip()
l = {'R', 'G', 'B'}
r = set()
g = set()
b = set()
for i, x in enumerate(S):
    if x == 'R':
        r.add(i)
    elif x == 'G':
        g.add(i)
    else:
        b.add(i)

ans = 0
for i, x in enumerate(S):
    for j, y in enumerate(S[i + 1:]):
        if x == y:
            continue
        else:
            j += i + 1
            s = (l - {x, y}).pop()
            if s == 'R':
                n = len(list(filter(lambda x: x > j, r)))
                if j + (j - i) in r:
                    ans += n - 1
                else:
                    ans += n
            elif s == 'G':
                n = len(list(filter(lambda x: x > j, g)))
                if j + (j - i) in g:
                    ans += n - 1
                else:
                    ans += n
            else:
                n = len(list(filter(lambda x: x > j, b)))
                if j + (j - i) in b:
                    ans += n - 1
                else:
                    ans += n

print(ans)

Submission status: Time Limit Exceeded

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

ans = 0

for x in range(n):
  for y in range(n):
    if not x < y:
      continue
    if s[x] == s[y]:
      continue
    for z in range(n):
      if not x < y < z:
        # print("SKIP: ", x, y, z)
        continue

      if "".join( sorted([s[x], s[y], s[z]]) ) != "BGR":
        # print("SKIP: ", x, y, z)
        continue

      if y-x == z-y:
        # print("SKIP: ", x, y, z)
        continue

      ans += 1
      # print(x, y, z)
      # print(s[x], s[y], s[z])

print(ans)

Submission status: Time Limit Exceeded

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

count = 0
char_candidates = "RGB"

for i in range(len(s)):
    for j in range(i+1, len(s)):
        i_char = s[i]
        j_char = s[j]
        
        if i_char == j_char:
            continue

        valid_k_char = char_candidates.replace(s[i], "").replace(s[j], "")

        target_chars = s[j+1:]
        match_count = target_chars.count(valid_k_char)

        if j + j - i < len(s) and s[j + j - i] == valid_k_char:
            match_count -= 1

        count += match_count

print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = [1 if i == 'R' else 2 if i == 'G' else 3 for i in input()]
r = 0
for i in range(0,n-2):
    for j in [d for d in range(i + 1,n - 1) if s[i] != s[d]]:
        for k in [f for f in range(j + 1,n) if s[i] != s[f] and s[j] != s[f] and j - i != f - j]:
            r += 1
else:
    print(r)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

N = int(input())
S = input()
ans = 0

def dfs(i):
    cnt = 0
    ls = []
    for j in range(i+1,N):
        if S[j] != S[i]:
            ls.append(j)
    for k in ls:
        for l in range(k+1,N):
            if S[k] != S[l] and S[l] != S[i] and(l-k != k-i):
                cnt += 1
    return cnt

ans = sum([dfs(m) for m in range(N)])
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
  n=int(input())
  s=tuple(input())
  r=[i for i, x in enumerate(s) if x == 'R']
  g=[i for i, x in enumerate(s) if x == 'G']
  b=[i for i, x in enumerate(s) if x == 'B']
  rg=r+g
  ans=0
  R,G=len(r),len(g)
  for i in r:
    for j in g:
      ans+=n-R-G +(-1 if ((i+j)%2==0  and (i+j)/2 in b) else 0) 
      x,y=((i+j)+abs(i-j)*3)/2,((i+j)-abs(i-j)*3)/2
      ans+=-1 if x in b else 0
      ans+=-1 if y in b else 0
  print(ans)
if __name__=='__main__':
  main()

Submission status: Time Limit Exceeded

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

rgb = 'RGB'
ans = 0
for i in range(0, n-2):
    for j in range(i+1,n-1):
        if s[i] == s[j]: continue
        k = rgb.replace(s[i], '')
        k = k.replace(s[j], '')
        r = s[j+1:2*j-i] + s[2*j-i+1:]
        ans += r.count(k)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()
count_r = s.count("R")
count_g = s.count("G")
count_b = s.count("B")
sum = count_r * count_g * count_b
minus = 0

for i in range(n-2):
    for j in range(1,(n-i)//2 + 1):
        if i+2*j <= n-1:
            tem = [s[i], s[i+j], s[i+2*j]]
            if tem[0] != tem[1] and tem[0] != tem[2] and tem[1] != tem[2]:
                minus += 1
            

print(sum - minus)

Submission status: Time Limit Exceeded

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

import queue

def main():
     n = int(input())
     s = input()

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

     ans = 0

     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)

     for i in range(n):
          if s[i] == 'R':
               spot = r_list.pop(0)
               ans += check(spot, g_list, b_list)

          if s[i] == 'G':
               spot = g_list.pop(0)
               ans += check(spot, r_list, b_list)

          if s[i] == 'B':
               spot = b_list.pop(0)
               ans += check(spot, r_list, g_list)

     print(ans)

def check(spot, first, second):
     ret = 0
     limit_first = first.copy()
     limit_second = second.copy()
     for f in first:
          ignore = f + (f - spot)
          limit_second = [s for s in limit_second if s > f]

          ret += len(limit_second)
          if ignore in limit_second:
               ret += -1

     for s in second:
          ignore = s + (s - spot)
          limit_first = [f for f in limit_first if f > s]

          ret += len(limit_first)
          if ignore in limit_first:
               ret += -1
     
     return ret

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()
r = 0
if n > 2:
    for i in range(n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                r += 1 if j - i != k - j and s[i] != s[j] and s[i] != s[k] and s[j] != s[k] else 0
print(r)

Submission status: Time Limit Exceeded

Solution code:
i = int(input())
l = str(input())
ll = len(l)

count = 0
for k in range(len(l)):
    for kk in range(len(l)):
        for kkk in range(len(l)):
            if l[k] != l[kk] and l[kk] != l[kkk] and l[k] != l[kkk] and k <= kk and kk <= kkk and (kk-k) != (kkk - kk):
                count+=1

print(count)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    N = int(input())
    S = input()
    cnt = {'R': [], 'B': [], 'G': []}
    indices_set = {'R': set(cnt['R']), 'G': set(cnt['G']), 'B': set(cnt['B'])}
    for i, c in enumerate(S):
        cnt[c].append(i)
    from itertools import permutations
    import bisect
    ans = 0
    for (ci, cj, ck) in permutations(['R', 'B', 'G']):
        for i in cnt[ci]:
            for ind_j in range(bisect.bisect_left(cnt[cj], i), len(cnt[cj])):
                j = cnt[cj][ind_j]
                ans += len(cnt[ck]) - bisect.bisect_left(cnt[ck], j)
                if j + (j - i) in cnt[ck]:
                    ans -= 1
    print(ans)
resolve()

Submission status: Time Limit Exceeded

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

bsize = len(b)
sum = 0
for r_num in r:
    for g_num in g:
        kari = 0
        if r_num>g_num:
            max=r_num
            min=g_num
        else:
            max=g_num
            min=r_num
    
        if (max-min)%2==0 and (((max-min)/2)+min) in b :
            kari -=1

        if (2*max-min) in b:
            kari -=1

        if (min-(max-min)) in b:
            kari -=1

        sum += bsize+kari

print (sum)

Submission status: Time Limit Exceeded

Solution code:
x = int(input())
d = list(input())
count = 0
for i in range(x):
  q = d[i]
  v = x - i - 1
  for j in range(v):
    p = i + j + 1
    w = d[p]
    c = v - j - 1
    for k in range(c):
      o = p + k + 1
      e = d[o]
      if q == e:
        pass
      elif w == q:
        pass
      elif e == w:
        pass
      elif o - p == p - i:
        pass
      else:
        count += 1

print(count)

Submission status: Time Limit Exceeded

Solution code:
# import sys 
# try:
# 	sys.stdin = open('input.txt', 'r') 
# 	sys.stdout = open('output.txt', 'w')
# except:
# 	pass
n = int(input())
s = input()
red = []
blue = []
green = []
for i in range(n):
	if s[i] == 'R':
		red.append(i)
	elif s[i] == "G":
		green.append(i)
	else:
		blue.append(i)
temp = [(len(red),'R'), (len(blue),'B'), (len(green),'G')]
temp.sort()

if temp[0][1] == 'R':
	first = list(red)
elif temp[0][1] == 'G':
	first = list(green)
else:
	first = list(blue)

if temp[1][1] == 'R':
	second = list(red)
elif temp[1][1] == 'G':
	second = list(green)
else:
	second = list(blue)

if temp[2][1] == 'R':
	third = list(red)
elif temp[2][1] == 'G':
	third = list(green)
else:
	third = list(blue)

final = []
for i in first:
	for j in second:
		gg = max(i,j)
		ss = min(i,j)
		diff = gg-ss
		check = []
		if (gg+ss)%2==0:
			check.append((gg+ss)//2)
		if gg+diff < n:
			check.append(gg+diff)
		if ss-diff >= 0:
			check.append(ss-diff)
		final.append(check)
# print(final)
# print(first,second,third)
ans = 0
ll = len(third)
for item in final:
	sub = 0
	for i in item:
		if i in third:
			sub += 1
	ans += ll - sub
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
ans = 0
for i in range(0,N):
    for j in range(i,N):
        if S[i] != S[j]:
            for k in range(j,N):
                if  j-i != k-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())
s = list(input())

#def my_index_multi(l, x):
#  return [i for i, _x in enumerate(l) if _x == x]
    
dic_inds = {
  "R":[],
  "G":[],
  "B":[]
}
for i,_x in enumerate(s):
  dic_inds[_x].append(i)
  
#r_inds = my_index_multi(s, "R")
#g_inds = my_index_multi(s, "G")
#b_inds = my_index_multi(s, "B")

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
s = list(input())

r = [i for i, x in enumerate(s) if x == 'R']
g = [i for i, x in enumerate(s) if x == 'G']
b = [i for i, x in enumerate(s) if x == 'B']
ans = 0

for x in r:
    n = [i for i in g if i>x]
    for y in n:
        m = [i for i in b if i>y]
        for z in m:
            if y-x != z-y:
                ans += 1
    n = [i for i in b if i>x]
    for y in n:
        m = [i for i in g if i>y]
        for z in m:
            if y-x != z-y:
                ans += 1

for x in b:
    n = [i for i in r if i>x]
    for y in n:
        m = [i for i in g if i>y]
        for z in m:
            if y-x != z-y:
                ans += 1
    n = [i for i in g if i>x]
    for y in n:
        m = [i for i in r if i>y]
        for z in m:
            if y-x != z-y:
                ans += 1           
                
for x in g:
    n = [i for i in r if i>x]
    for y in n:
        m = [i for i in b if i>y]
        for z in m:
            if y-x != z-y:
                ans += 1              
    n = [i for i in b if i>x]
    for y in n:
        m = [i for i in r if i>y]
        for z in m:
            if y-x != z-y:
                ans += 1

print(ans)

Submission status: Time Limit Exceeded

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

R, G, B = [], [], []
for i, c in enumerate(s):
  if c == 'R': R.append(i)
  elif c == 'G': G.append(i)
  else: B.append(i)

d = dict({'R':len(R), 'G':len(G), 'B':len(B)})
ds = sorted(d.items(), key=lambda x: x[1])

if ds[0][0] == 'R': X1 = R
elif ds[0][0] == 'G': X1 = G
else: X1 = B
if ds[1][0] == 'R': X2 = R
elif ds[1][0] == 'G': X2 = G
else: X2 = B
if ds[2][0] == 'R': X3 = R
elif ds[2][0] == 'G': X3 = G
else: X3 = B

ans = 0
for a in X1:
  for b in X2:
    if a < b: x, y = a, b
    else: x, y = b, a

    ans += len(X3)
    if x*2 - y >= 0:
      if x*2 - y in X3: ans -= 1
    if (x + y) % 2 == 0:
      if (x+y)//2 in X3: ans -= 1
    if y*2 - x in X3: ans -= 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

    
def main():

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

    if N < 3:
        print(0)
        exit()

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

    R_ite = 0
    G_ite = 0
    B_ite = 0

    sum = 0

    for i in range(len(S)):
        if S[i] == 'R':
            R.append(i)
        elif S[i] == 'G':
            G.append(i)
        else:
            B.append(i)

    # print(R)
    # print(G)
    # print(B)

    rgb = {'R', 'G', 'B'}

    for i in range(len(S)-2):
        tmp_set = {S[i]}
        for j in range(i+1,len(S)-1):
            if S[i] != S[j]:
                tmp_set.add(S[j])
                target = rgb - tmp_set
                target = target.pop()
                tmp_list = []
                if target == 'R':
                    tmp_list = R
                elif target == 'G':
                    tmp_list = G
                else:
                    tmp_list = B
                sum += len([num for num in tmp_list if num > j and num-j != j -i])
                tmp_set = {S[i]}

    print(sum)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
X = int(input())
S = str(input())
a = 0

for i in range(X):
   for j in range(i+1,X):
      if S[j] != S[i]:
        for k in range(j+1,X):
          if (j - i) != (k - j) and S[k] != S[i] and S[k] != S[j]:
            a = a + 1
        
print(a)

Submission status: Time Limit Exceeded

Solution code:
import sys
import bisect
readline = sys.stdin.readline

def main():
	a = [1,2,3,4,5]
	n = int(input())
	s = tuple(input())

	ans = 0
	r = []
	g = []
	b = []
	for i in range(3):
		if s[i] == 'R':
			r.append(i)
		elif s[i] == 'G':
			g.append(i)
		else:
			b.append(i)

	for i in range(3,n):
		if s[i] == 'R':
			r.append(i)
		elif s[i] == 'G':
			g.append(i)
		else:
			b.append(i)

		for j in range(i-2):
			if s[i] == s[j]:
				continue
			elif 'R' not in [s[i],s[j]]:
				ans += bisect.bisect_left(r,i) - bisect.bisect_left(r,j)
				index = bisect.bisect_left(r,j + (i-j)//2 )
				if index < len(r):
					if (i-j) % 2 == 0 and r[index] == j + (i-j)//2:
						ans -= 1
			elif 'G' not in [s[i],s[j]]:
				ans += bisect.bisect_left(g,i) - bisect.bisect_left(g,j)
				index = bisect.bisect_left(g,j + (i-j)//2 )
				if index < len(g):
					if (i-j) % 2 == 0 and g[index] == j + (i-j)//2:
						ans -= 1
			elif 'B' not in [s[i],s[j]]:
				ans += bisect.bisect_left(b,i) - bisect.bisect_left(b,j)
				index = bisect.bisect_left(b,j + (i-j)//2 )
				if index < len(b):
					if (i-j) % 2 == 0 and b[index] == j + (i-j)//2:
						ans -= 1

	print(ans)

if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
S = input()
L_r = []
L_g = []
L_b = []
ans = 0
for i in range(N):
    if S[i] == "R":
        L_r.append(i)
    elif S[i] == "G":
        L_g.append(i)
    else:
        L_b.append(i)
m = min(len(L_r),len(L_g),len(L_b))
if len(L_r) == m:
    for x in L_g:
        for y in L_b:
            ans += m
            if 2*x - y in L_r:
                ans -= 1
            if 2*y - x in L_r:
                ans -= 1
            if (x + y) % 2 == 0 and (x + y) // 2 in L_r:
                ans -= 1
elif len(L_g) == m:
    for x in L_r:
        for y in L_b:
            ans += m
            if 2*x - y in L_g:
                ans -= 1
            if 2*y - x in L_g:
                ans -= 1
            if (x + y) % 2 == 0 and (x + y) // 2 in L_g:
                ans -= 1
else:
    for x in L_r:
        for y in L_g:
            ans += m
            if 2*x - y in L_b:
                ans -= 1
            if 2*y - x in L_b:
                ans -= 1
            if (x + y) % 2 == 0 and (x + y) // 2 in L_b:
                ans -= 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

def main():
    N = int(input())
    S = input()
    dict = {"R":[],"G":[],"B":[]}
    ans = 0
    for i in range(N):
        dict[S[i]].append(i)
    l = {"R" :len(dict["R"]),"G" :len(dict["G"]),"B" :len(dict["B"])}
    name = [["R","G","B"], ["R","B","G"], ["G","R","B"],["G","B","R"],["B","R","G"],["B","G","R"]]
    for i in name:
        a,b,c = i
        for i in dict[a]:
            p = bisect.bisect_left(dict[b],i+1)
            if p >= l[b]:
                continue
            for j in dict[b][p:]:
                for k in range(l[c]):
                    if dict[c][k] > j and (j - i) != (dict[c][k] - j):
                        ans += 1

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