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

Solution (Python):

import os
import sys
from io import BytesIO, IOBase
from math import gcd

def main():
		n = int(input())
		s = input()
		ans = 0
		b = [0]*n
		g = [0]*n
		r = [0]*n
		for i in range(n):
			if s[i]=="B":
				b[i]=1
			if s[i]=="G":
				g[i]=1
			if s[i]=="R":
				r[i]=1
		pre_r = [r[0]]
		pre_b = [b[0]]
		pre_g = [g[0]]
		for i in range(1,n):
			pre_r.append(pre_r[i-1]+r[i])
			pre_g.append(pre_g[i-1]+g[i])
			pre_b.append(pre_b[i-1]+b[i])	
		ms = {"R", "G", "B"}
		ans = 0
		for i in range(n):
			for j in range(i+1, n):
				if (s[i]!=s[j]):
					z = set([s[i], s[j]])
					x = list(ms.difference(z))[0]
					
					if x=="B":
						tmp = pre_b[j]-pre_b[i]
						if (i+j)/2 == int((i+j)/2):
							if b[(i+j)//2] == 1:
								tmp-=1
						ans += max(0, tmp)
					if x=="G":
						tmp = pre_g[j]-pre_g[i]
						
						if (i+j)/2 == int((i+j)/2):
							
							
							if g[(i+j)//2] == 1:
								tmp-=1
								
						ans += max(0, tmp)					
					if x=="R":
						tmp = pre_r[j]-pre_r[i]
						if (i+j)/2 == int((i+j)/2):
							if r[(i+j)//2] == 1:
								tmp-=1
						ans += max(0, tmp)
		print(ans)
		
		




BUFSIZE = 8192


class FastIO(IOBase):
	newlines = 0

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

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
		self.newlines = 0
		return self.buffer.read()

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

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


class IOWrapper(IOBase):
	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode("ascii"))
		self.read = lambda: self.buffer.read().decode("ascii")
		self.readline = lambda: self.buffer.readline().decode("ascii")


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



if __name__ == "__main__":
	main()

Solution (Python):



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


def main():
    r, g, b = 0, 0, 0
    rg, gr = 0, 0
    rb, br = 0, 0
    gb, bg = 0, 0
    ans = 0
    for s in S[::-1]:
        if s == "R":
            ans += gb + bg
            rg += g
            rb += b
            r += 1
        if s == "G":
            ans += rb + br
            gr += r
            gb += b
            g += 1
        if s == "B":
            ans += rg + gr
            br += r
            bg += g
            b += 1
    
    lim = (N - 1) // 2 + 1
    for i in range(1, lim):
        lim2 = N - 2 * i
        for j in range(lim2):
            if S[j] != S[j+i] and S[j+i] != S[j+2*i] and S[j] != S[j+2*i]:
                ans -= 1
    
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
S = input()
R = [0]*N
G = [0]*N
B = [0]*N
out = 0
for i in range(N):
    if S[i]=="R":
        R[i]+=1
    if S[i]=="G":
        G[i]+=1
    if S[i]=="B":
        B[i]+=1

SB = sum(B)
for i in range(N):
    for j in range(N):
        X = R[i]
        Y = G[j]
        if (X==1)and(Y==1):
            out += SB
            D = abs(i-j)

            L1 = max(i,j)+D
            if L1<N:
                out += -1*B[L1]
            L2 = min(i,j)-D
            if 0<=L2:
                out += -1*B[L2]
            if D%2==0:
                L3 = min(i,j)+D//2
                out += -1*B[L3]
print(out)

Solution (Python):

import sys


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

r_ruiseki = [0]*(N+1)
b_ruiseki = [0]*(N+1)
g_ruiseki = [0]*(N+1)
for i in range(N):
    r_ruiseki[i+1] = r_ruiseki[i] + (S[i]=='R')
    g_ruiseki[i+1] = g_ruiseki[i] + (S[i]=='G')
    b_ruiseki[i+1] = b_ruiseki[i] + (S[i]=='B')
pos_r = []
pos_b = []
pos_g = []
for i,s in enumerate(S):
    if s=='R':
        pos_r.append(i)
    elif s=='B':
        pos_b.append(i)
    else:
        pos_g.append(i)

ans = 0
for i in pos_r:
    for j in pos_b:
        if j-i<=1:
            continue
        ans += g_ruiseki[j+1] - g_ruiseki[i]
        if (i&1 == j&1):
            if S[(i+j)//2]=='G':
                ans -= 1
    

for i in pos_b:
    for j in pos_r:
        if j-i<=1:
            continue
        ans += g_ruiseki[j+1] - g_ruiseki[i]
        if (i&1 == j&1):
            if S[(i+j)//2]=='G':
                ans -= 1
    

for i in pos_r:
    for j in pos_g:
        if j-i<=1:
            continue
        ans += b_ruiseki[j+1] - b_ruiseki[i]
        if (i&1 == j&1):
            if S[(i+j)//2]=='B':
                ans -= 1
    
for i in pos_g:
    for j in pos_r:
        if j-i<=1:
            continue
        ans += b_ruiseki[j+1] - b_ruiseki[i]
        if (i&1 == j&1):
            if S[(i+j)//2]=='B':
                ans -= 1
    

for i in pos_g:
    for j in pos_b:
        if j-i<=1:
            continue
        ans += r_ruiseki[j+1] - r_ruiseki[i]
        if (i&1 == j&1):
            if S[(i+j)//2]=='R':
                ans -= 1
    
for i in pos_b:
    for j in pos_g:
        if j-i<=1:
            continue
        ans += r_ruiseki[j+1] - r_ruiseki[i]
        if (i&1 == j&1):
            if S[(i+j)//2]=='R':
                ans -= 1
    

print(ans)

Solution (Python):
N = int(input())
S = input()
r = S.count("R")
g = S.count("G")
b = S.count("B")
cou = 0
for i in range((N - 3) // 2 + 1):
    for j in range(N - 2 - 2 * i):
        if S[j] != S[i + j + 1] and S[i + j + 1] != S[2 * i + j + 2] and S[j] != S[2 * i + j + 2]:
            cou += 1
print(r * g * b - cou)

Solution (Python):
n = int(input())
s = input()
ans = s.count('R')*s.count('G')*s.count('B')
for begin in range(n):
    step = 1
    while begin+2*step<n:
        if s[begin]!=s[begin+step] and s[begin+step]!=s[begin+2*step] and s[begin+2*step]!=s[begin]:
            ans -= 1
        step += 1
print(ans)

Solution (Python):
import bisect
import copy
import heapq
import sys
import itertools
import math
import queue
input = sys.stdin.readline
sys.setrecursionlimit(100000)


def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if n is None:
            return

        if self.v is None:
            self.v = n
            return
        self.v = self.f(self.v, n) 


def main():
    N = int(input())
    S = input().strip()
    
    v = 0
    R = 0
    G = 0
    B = 0
    for i in range(N):
        if S[i] == "R":
            R += 1
        elif S[i] == "G":
            G += 1
        else:
            B += 1

        if i == 0 or i == N - 1:
            continue

        for d in range(1, min(i, N - i - 1) + 1):
            if S[i] == S[i - d]:
                continue
            if S[i] == S[i + d]:
                continue
            if S[i - d] == S[i + d]:
                continue
            v += 1

    print(R * G * B - v)

if __name__ == "__main__":
    main()

Solution (Python):
def solve(n, s):

    r_list = [i for i in range(n) if s[i] == "R"]
    g_list = [i for i in range(n) if s[i] == "G"]
    
    b_dict = {i: 1 for i in range(n) if s[i] == "B"}

    res = len(r_list) * len(g_list) * len(b_dict.keys())
    for i in r_list:
        for j in g_list:
            
            m, n = min(i, j), max(i, j)
            if n + (n - m) in b_dict.keys():
                res -= 1
            if m - (n - m) in b_dict.keys():
                res -= 1
            if (n - m) % 2 == 0 and (n + m) // 2 in b_dict.keys():
                res -= 1

    return res


def main():
    n = int(input())
    s = input()
    res = solve(n, s)
    print(res)


def test():
    assert solve(4, "RRGB") == 1
    assert solve(39, "RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB") == 1800


if __name__ == "__main__":
    test()
    main()

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

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

ans=r*g*b
for i in range(1,n):
    for j in range(n):
        if(j+i*2>=n):break
        d1,d2,d3=s[j],s[j+i],s[j+i*2]
        if(not(d1==d2 or d2==d3 or d1==d3)):ans-=1
print(ans)

Solution (Python):
n = int(input())
s = input()
r = [0]*n
g = [0]*n
b = [0]*n
if s[0] == "R": r[0] = 1
elif s[0] == "G": g[0] = 1
else: b[0] = 1
for i in range(1,n):
    if s[i] == "R": r[i] = 1
    elif s[i] == "G": g[i] = 1
    else: b[i] = 1
    r[i] += r[i-1]
    g[i] += g[i-1]
    b[i] += b[i-1]
ans = 0
for i in range(n):
    for j in range(i+1,n):
        if s[i] == s[j]: continue
        d = j - i
        t = (s[i],s[j])
        if "R" not in t:
            ans += r[n-1]-r[j]
            if j+d >= n: continue
            if s[j+d] == "R": ans -= 1
        elif "G" not in t:
            ans += g[n-1]-g[j]
            if j+d >= n: continue
            if s[j+d] == "G": ans -= 1
        else:
            ans += b[n-1]-b[j]
            if j+d >= n: continue
            if s[j+d] == "B": ans -= 1
        
print(ans)

Solution (Python):

N=int(input())
S=list(input())
RGB=[[0,0,0] for i in range(N)]

ans=0

for i in range(1,N):
    k=-i
    if S[k]=="R":
        RGB[k-1][0]=RGB[k][0]+1
        RGB[k-1][1]=RGB[k][1]
        RGB[k-1][2]=RGB[k][2]
    elif S[k]=="G":
        RGB[k-1][0]=RGB[k][0]
        RGB[k-1][1]=RGB[k][1]+1
        RGB[k-1][2]=RGB[k][2]
    elif S[k]=="B":
        RGB[k-1][0]=RGB[k][0]
        RGB[k-1][1]=RGB[k][1]
        RGB[k-1][2]=RGB[k][2]+1

for i in range(N):
    for j in range(i,N):
        if S[i]!=S[j]:
            if S[i]=="R" and S[j]=="G" or S[i]=="G" and S[j]=="R":
                ans+=RGB[j][2]
                if 2*j-i<N:
                    if RGB[j][2]>0 and S[2*j-i]=="B":
                        ans-=1
            elif S[i]=="R" and S[j]=="B" or S[i]=="B" and S[j]=="R":
                ans+=RGB[j][1]
                if 2*j-i<N:
                    if RGB[j][1]>0 and S[2*j-i]=="G":
                        ans-=1
            elif S[i]=="B" and S[j]=="G" or S[i]=="G" and S[j]=="B":
                ans+=RGB[j][0]
                if 2*j-i<N:
                    if RGB[j][0]>0 and S[2*j-i]=="R":
                        ans-=1

print(ans)

Solution (Python):
import math
import fractions



def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans
'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  
factinv = [1, 1]  
inv = [0, 1]  

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''








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

num = [[0,0,0,0,0] for i in range(n)]
ans = 0

info = []
for i in range(n):
    if(s[i]=='R'):
        info.append(0)
    elif(s[i]=='G'):
        info.append(1)
    else:
        info.append(2)
        


for i in range(n):
    for j in range(i):
        if((3+info[i]-info[j])%3 == 1):
            num[i][0]+=1
        elif((3+info[i]-info[j])%3 == 2):
            num[i][1]+=1
    for j in range(n-1-i):
        if((3+info[i] - info[i+1+j])%3 == 1):
            num[i][2]+=1
        elif((3+info[i] - info[i+1+j])%3 == 2):
            num[i][3]+=1
    for j in range(min(i,n-1-i)):
        if(s[i-j-1]!=s[i+1+j] and s[i]!=s[i-j-1] and s[i]!=s[i+1+j]):
            num[i][4]+=1
            
    
    ans += num[i][0]*num[i][3] + num[i][1]*num[i][2] - num[i][4]

    
print(ans)

Solution (Python):
N = int(input())
R = [0]*N
G = [0]*N
B = [0]*N
S = input()
R_sum,G_sum,B_sum = 0,0,0
for i in range(N):
    if(S[i]=="R"):
        R_sum += 1
        R[i] = R_sum
    elif(S[i] == "G"):
        G_sum += 1
        G[i] = G_sum
    else:
        B_sum += 1
        B[i] = B_sum
ans = 0
for i in range(0,N-1):
    for j in range(i+1,N):
        if((S[i] == "R" and S[j] == "G") or (S[i] == "G" and S[j] == "R")):
            ans += B[N-1]-B[j]
            point_index = j+(j-i)
            if(point_index >= N):
                continue
            elif(S[point_index]=="B"):
                    ans -= 1
        elif((S[i] == "G" and S[j] == "B") or (S[i] == "B" and S[j] == "G")):
            ans += R[N-1]-R[j]
            point_index = j+(j-i)
            if(point_index >= N):
                continue
            elif(S[point_index]=="R"):
                    ans -= 1
        elif((S[i] == "R" and S[j] == "B") or (S[i] == "B" and S[j] == "R")):
            ans += G[N-1]-G[j]
            point_index = j+(j-i)
            if(point_index >= N):
                continue
            elif(S[point_index]=="G"):
                    ans -= 1
print(ans)

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

a = {}
a['R'] = [0 for _ in range(n + 1)]
a['G'] = [0 for _ in range(n + 1)]
a['B'] = [0 for _ in range(n + 1)]

for i, si in enumerate(s):
    a['R'][i + 1] += a['R'][i]
    a['G'][i + 1] += a['G'][i]
    a['B'][i + 1] += a['B'][i]
    a[si][i + 1] += 1

ans = 0
for i, si in enumerate(s):
    if si == 'R':
        keys = ['G', 'B']
    elif si == 'G':
        keys = ['B', 'R']
    else:
        keys = ['R', 'G']
    x = a[keys[0]][-1] - a[keys[0]][i + 1]
    y = a[keys[1]][-1] - a[keys[1]][i + 1]
    ans += x * y
    for j in range(1, (n - i + 1) // 2):
        sj = s[i + j]
        sk = s[i + 2 * j]
        if sj != sk and sj in keys and sk in keys:
            ans -= 1
print(ans)

Solution (Python):
N = int(input())
S = input()
R = S.count("R")
G = S.count("G")
ans = R*G*(N-R-G)

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

            
print(ans)

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

R_cnt = S.count("R")
G_cnt = S.count("G")
B_cnt = S.count("B")
cnt = 0
for i in range(N):
    for j in range(i+1, N):
        if S[i] != S[j] and ((2*j - i) < N):
            if S[2*j - i] != S[i] and S[2*j - i] != S[j]:
                cnt += 1

print(R_cnt*G_cnt*B_cnt-cnt)

Solution (Python):
import copy
n = int(input())
S = list(input())

table = [{}]
cnt = {'R': 0, 'G': 0, 'B': 0}
for s in S:
    cnt[s] += 1
    table.append([s, copy.deepcopy(cnt)])

RGB = set(['R', 'G', 'B'])
ans = 0
for i in range(1, n + 1):
    for j in range(i + 1, n + 1):
        if table[i][0] != table[j][0]:
            kigou_set = RGB ^ set([table[i][0], table[j][0]])
            kigou = list(kigou_set)[0]
            sa = table[-1][1][kigou] - table[j][1][kigou]
            ans += sa
            l = j + (j - i)
            
            if l <= n:
                if table[l][0] == kigou:
                    
                    ans -= 1
                
print(ans)

Solution (Python):
N = int(input())
S = " "+input()
pos = [[0 for _ in range(4000*2+10)] for _ in range(3)]
s = [0 for _ in range(3)]

for i in range(1, N+1):
    if S[i] == "R":
        pos[0][i] = 1
        s[0] += 1
    elif S[i] == "G":
        pos[1][i] = 1
        s[1] += 1 
    else:
        pos[2][i] = 1
        s[2] += 1

ans = 0
for i in range(N+1):
    if pos[0][i] == 0:
        continue
    for j in range(N+1):
        if pos[1][j] == 0:
            continue
        ans += s[2]
        if 2*i-j >= 0 and pos[2][2*i-j] == 1:
            ans -= 1
        if 2*j-i >= 0 and pos[2][2*j-i] == 1:
            ans -= 1
        if (i+j)%2 == 0 and pos[2][(i+j)//2] == 1:
            ans -= 1

print(ans)

Solution (Python):
from math import *
n = int(input())
s = input()
r = 0
b = 0
g = 0
ans = 0
for i in range(n):
	rf = s[:i].count('R')
	rb = s[i:].count('R')
	bf = s[:i].count('B')
	bb = s[i:].count('B')
	gf = s[:i].count('G')
	gb = s[i:].count('G')
	if(s[i] == 'R'):
		ans += bf*gb + bb*gf
		for j in range(i+1):
			if i+j >= n:
				break
			if(s[i-j] == 'B' and s[i+j] == 'G') or (s[i-j] == 'G' and s[i+j] == 'B'):
				ans -= 1
	elif(s[i] == 'B'):
		ans += rf*gb + rb*gf
		for j in range(i+1):
			if i+j >= n:
				break
			if(s[i-j] == 'R' and s[i+j] == 'G') or (s[i-j] == 'G' and s[i+j] == 'R'):
				ans -= 1
	else:
		ans += rf*bb + rb*bf
		for j in range(i+1):
			if i+j >= n:
				break
			if(s[i-j] == 'R' and s[i+j] == 'B') or (s[i-j] == 'B' and s[i+j] == 'R'):
				ans -= 1
print(ans)

Solution (Python):
n = int(input())
s = input()
rui = [[0] * (n) for i in range(3)]

if s[0] == "R":
    rui[0][0] = 1
elif s[0] == "G":
    rui[1][0] = 1
else:
    rui[2][0] = 1

for i in range(n-1):
    for j in range(3):
        rui[j][i+1] = rui[j][i]
    
    if s[i+1] == "R":
        rui[0][i+1] += 1
    elif s[i+1] == "G":
        rui[1][i+1] += 1
    else:
        rui[2][i+1] += 1

mi = 0
an = 0
for i in range(1,n-1):
    if s[i] == "R":
        x = min(i,n-1-i)
        for j in range(1,x+1):
            if (s[i+j] == "G" and s[i-j] == "B") or (s[i+j] == "B" and s[i-j] == "G"):
                mi += 1
        an += (rui[1][i-1] * (rui[2][n-1] - rui[2][i]))
        an += (rui[2][i-1] * (rui[1][n-1] - rui[1][i]))
                
    elif s[i] == "G":
        x = min(i,n-1-i)
        for j in range(1,x+1):
            if (s[i+j] == "R" and s[i-j] == "B") or (s[i+j] == "B" and s[i-j] == "R"):
                mi += 1
        an += (rui[0][i-1] * (rui[2][n-1] - rui[2][i]))
        an += (rui[2][i-1] * (rui[0][n-1] - rui[0][i]))
                
    elif s[i] == "B":
        x = min(i,n-1-i)
        for j in range(1,x+1):
            if (s[i+j] == "R" and s[i-j] == "G") or (s[i+j] == "G" and s[i-j] == "R"):
                mi += 1
        
        an += (rui[0][i-1] * (rui[1][n-1] - rui[1][i]))
        an += (rui[1][i-1] * (rui[0][n-1] - rui[0][i]))
        
print(an-mi)

Solution (Python):
from itertools import accumulate

n = int(input())
s = input()
d = {'R':1, 'G':2, 'B':3}
ss = list(map(d.get, s))
r = list(accumulate([i == 1 for i in ss]))
g = list(accumulate([i == 2 for i in ss]))
b = list(accumulate([i == 3 for i in ss]))
ans = 0
for i in range(1,n-1):
    if ss[i] == 1:
        tmp = g[i-1] * (b[-1] - b[i-1]) + b[i-1] * (g[-1] - g[i-1])
    elif ss[i] == 2:
        tmp = r[i-1] * (b[-1] - b[i-1]) + b[i-1] * (r[-1] - r[i-1])
    elif ss[i] == 3:
        tmp = r[i-1] * (g[-1] - g[i-1]) + g[i-1] * (r[-1] - r[i-1])

    ans += tmp
    

for i in range(n-2):
    for j in range(i+1, n-1):
        idx =  2*j-i
        if idx >= n:
            break
        if ss[i] != ss[j] and ss[j] != ss[idx] and ss[idx] != ss[i]:
            
            ans -= 1

print(ans)

Solution (Python):
from itertools import accumulate

def solve():
    N = int(input())
    Ss = input().rstrip()

    Rs, Gs, Bs = [], [], []
    numRs = [0] * N
    numGs = [0] * N
    numBs = [0] * N
    for i in range(N):
        S = Ss[i]
        if S == 'R':
            Rs.append(i)
            numRs[i] = 1
        elif S == 'G':
            Gs.append(i)
            numGs[i] = 1
        else:
            Bs.append(i)
            numBs[i] = 1

    lenR, lenG, lenB = len(Rs), len(Gs), len(Bs)
    setR = set(Rs)
    setG = set(Gs)
    setB = set(Bs)

    accNumRevRs = list(accumulate(numRs[::-1]))[::-1]
    accNumRevGs = list(accumulate(numGs[::-1]))[::-1]
    accNumRevBs = list(accumulate(numBs[::-1]))[::-1]

    ans = 0
    for j in range(N):
        S = Ss[j]
        if S == 'R':
            for i in Gs:
                if i > j:
                    break
                ans += accNumRevBs[j]
                k = 2*j-i
                if k in setB:
                    ans -= 1
            for i in Bs:
                if i > j:
                    break
                ans += accNumRevGs[j]
                k = 2*j-i
                if k in setG:
                    ans -= 1
        elif S == 'G':
            for i in Rs:
                if i > j:
                    break
                ans += accNumRevBs[j]
                k = 2*j-i
                if k in setB:
                    ans -= 1
            for i in Bs:
                if i > j:
                    break
                ans += accNumRevRs[j]
                k = 2*j-i
                if k in setR:
                    ans -= 1
        else:
            for i in Rs:
                if i > j:
                    break
                ans += accNumRevGs[j]
                k = 2*j-i
                if k in setG:
                    ans -= 1
            for i in Gs:
                if i > j:
                    break
                ans += accNumRevRs[j]
                k = 2*j-i
                if k in setR:
                    ans -= 1

    print(ans)


solve()

Solution (Python):

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

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

ans = r * g * b


for i in range(n):
    for j in range(1, n // 2 + 1):
        if i-j < 0 or i+j > n-1:
            break
        if s[i] != s[i-j] and s[i] != s[i+j] and s[i-j] != s[i+j]:
            ans -= 1
print(ans)

Solution (Python):
N=int(input())
S=input()
dr={}
dg={}
db={}
for i in range(N):
    if S[i]=="R":
        dr[i]=1
    elif S[i]=="G":
        dg[i]=1
    else:
        db[i]=1
lendb=len(db)
ans=0
for r in dr:
    for g in dg:
        ans+=lendb-(2*r-g in db)-(2*g-r in db)-((r+g)/2 in db)
print(ans)

Solution (Python):
n = int(input())
lis = str(input())
r = []
g = []
b = []
for i in range(n):
  if lis[i] == "R":
    r.append(i)
  elif lis[i] == "G":
    g.append(i)
  else:
    b.append(i)
ans = len(r) * len(g) * len(b)
for i in range(1,n-1):
  for j in range(i+1,n):
    if i != j and 2 * j -i <= n:
      k = j + (j-i)
      if (lis[i-1] != lis[j-1]) and (lis[j-1] != lis[k-1]) and (lis[k-1] != lis[i-1]):
        ans -= 1
print(ans)

Solution (Python):
from collections import defaultdict
N=int(input())
L=input()
Hash=defaultdict(lambda:0)
for i in L:
    Hash[i]+=1
ans=Hash['G']*Hash['R']*Hash['B']
for j in range(2*N//3+1):
    diff=j
    for i in range(N-2*diff):
        if L[i+diff]!=L[i] and L[i+2*diff]!=L[i] and L[i+2*diff]!=L[i+diff]:
            ans-=1
print(ans)

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


RGB = [[0]*(N+1) for i in range(3)]
for i in range(N-1,-1,-1):
    if S[i] == "R":
        RGB[0][i] = RGB[0][i+1]+1
        RGB[1][i] = RGB[1][i+1]
        RGB[2][i] = RGB[2][i+1]
    elif S[i] == "G":
        RGB[0][i] = RGB[0][i+1]
        RGB[1][i] = RGB[1][i+1]+1
        RGB[2][i] = RGB[2][i+1]
    else:
        RGB[0][i] = RGB[0][i+1]
        RGB[1][i] = RGB[1][i+1]
        RGB[2][i] = RGB[2][i+1]+1

ans = 0
for i in range(N-2):
    for j in range(i+1,N-1):
        if (S[i] == "R" and S[j] == "G") or (S[i] == "G" and S[j] == "R"):
            ans += RGB[2][j]
            if j+(j-i) < N and S[j+(j-i)] == "B":
                ans -= 1
        elif (S[i] == "G" and S[j] == "B") or (S[i] == "B" and S[j] == "G"):
            ans += RGB[0][j]
            if j+(j-i) < N and S[j+(j-i)] == "R":
                ans -= 1
        elif (S[i] == "R" and S[j] == "B") or (S[i] == "B" and S[j] == "R"):
            ans += RGB[1][j]
            if j+(j-i) < N and S[j+(j-i)] == "G":
                ans -= 1
print(ans)

Solution (Python):

import sys


def solve(N: int, S: str):
    r = S.count("R")
    g = S.count("G")
    b = S.count("B")

    minus = 0
    for k in range(2000):
        if k * 2 + 3 > N:
            break
        for i in range(N-k*2-2):
            if S[i] != S[i+k+1] and S[i] != S[i+2*k+2] and S[i+k+1] != S[i+2*k+2]:
                minus += 1

    print(r*g*b - minus)

    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    S = next(tokens)  
    solve(N, S)

if __name__ == '__main__':
    main()

Solution (Python):
def main():
    N = int(input())
    S = input()

    rcs = [0] * N
    gcs = [0] * N
    bcs = [0] * N

    for i in range(N):
        if S[i] == 'R':
            rcs[i] = 1
        elif S[i] == 'G':
            gcs[i] = 1
        elif S[i] == 'B':
            bcs[i] = 1

    for i in range(1, N):
        rcs[i] += rcs[i - 1]
        gcs[i] += gcs[i - 1]
        bcs[i] += bcs[i - 1]

    result = 0
    for i in range(N):
        if S[i] == 'R':
            for j in range(i + 1, N):
                if S[j] == 'R':
                    continue
                elif S[j] == 'G':
                    result += bcs[N - 1] - bcs[j]
                    t = 2 * j - i
                    if t < N and S[t] == 'B':
                        result -= 1
                elif S[j] == 'B':
                    result += gcs[N - 1] - gcs[j]
                    t = 2 * j - i
                    if t < N and S[t] == 'G':
                        result -= 1
        elif S[i] == 'G':
            for j in range(i + 1, N):
                if S[j] == 'G':
                    continue
                elif S[j] == 'R':
                    result += bcs[N - 1] - bcs[j]
                    t = 2 * j - i
                    if t < N and S[t] == 'B':
                        result -= 1
                elif S[j] == 'B':
                    result += rcs[N - 1] - rcs[j]
                    t = 2 * j - i
                    if t < N and S[t] == 'R':
                        result -= 1
        elif S[i] == 'B':
            for j in range(i + 1, N):
                if S[j] == 'B':
                    continue
                elif S[j] == 'R':
                    result += gcs[N - 1] - gcs[j]
                    t = 2 * j - i
                    if t < N and S[t] == 'G':
                        result -= 1
                elif S[j] == 'G':
                    result += rcs[N - 1] - rcs[j]
                    t = 2 * j - i
                    if t < N and S[t] == 'R':
                        result -= 1
    print(result)


main()

Solution (Python):
from collections import defaultdict
def build_dp (s) :
    temp = [0,0,0] 
    for c in s :
        if c == "R" :
            temp[0] += 1
        elif c == "G" :
            temp[1] += 1
        else :
            temp[2] += 1
    return temp

def choose3 (n) :
    return (n*(n-1)*(n-2))//6

def choose2 (n) :
    return (n*(n-1))//2

def d(n, s) :
    dp = build_dp(s)
    all_pos = choose3(n)
    for i in range(3) :
        all_pos -= choose3(dp[i])
        for j in range(3) :
            if i == j :
                continue
            all_pos -= choose2(dp[i])*dp[j]

    for i in range(n) :
        for j in range(1,n) :
            if i-j < 0 or i+j >= n :
                break 
            if s[i-j] != s[i] and s[i+j] != s[i] and s[i-j] != s[i+j] :
                all_pos -= 1
    
    return all_pos

if __name__ == "__main__" :
    n = int(input())
    s = input()
    print(d(n, s))

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

r = [0 for _ in range(n)]
g = [0 for _ in range(n)]
b = [0 for _ in range(n)]

for i in range(len(s)):
    if s[i] == "R":
        r[i] += 1
    elif s[i] == "G":
        g[i] += 1
    else:
        b[i] += 1
        
for i in range(1,len(s)):
    r[i] += r[i - 1]
    g[i] += g[i - 1]
    b[i] += b[i - 1]

dic = {'GR': b, 'BG': r, 'BR': g}
col = {'GR': "B", 'BG': "R", 'BR': "G"}

ans = 0

for i in range(n - 2):
    for j in range(i + 1, n - 1):
        if s[i] != s[j]:
            used_color = "".join(sorted(list(s[i] + s[j])))
            arr = dic[used_color]
            ans += arr[-1] - arr[j]
            if j + j - i < n:
                if s[j + j - i] == col[used_color]:
                    ans -= 1
print(ans)

Solution (Python):
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)
ans = 0
R = len(r)
G = len(g)
for i in range(R):
    for j in range(G):
        x = r[i]
        y = g[j]
        if x > y:
            x, y = y, x
        num = len(b)
        if 2 * x - y >= 0 and S[2 * x - y] == 'B':
            num -= 1
        if (x+y)%2 == 0 and S[(x+y)//2] == 'B':
            num -= 1
        if 2 * y - x < N and S[2 * y - x] == 'B':
            num -= 1
        ans += num
print(ans)

Solution (Python):


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

    r_cnt = [0 for _ in range(n)]
    g_cnt = [0 for _ in range(n)]
    b_cnt = [0 for _ in range(n)]

    for i in reversed(range(n)):
        if s[i] == 'R':
            r_cnt[i] = 1
        if s[i] == 'G':
            g_cnt[i] = 1
        if s[i] == 'B':
            b_cnt[i] = 1

    for i in reversed(range(1, n)):
        r_cnt[i - 1] += r_cnt[i]
        g_cnt[i - 1] += g_cnt[i]
        b_cnt[i - 1] += b_cnt[i]


    ans = 0
    for i in range(n - 2):
        for j in range(i + 1, n - 1):
            if s[i] == s[j]:
                continue
            dist = j - i
            if {s[i], s[j]} == {'R', 'G'}:
                ans += b_cnt[j + 1]
                if j + dist < n and s[j + dist] == 'B':
                    ans -= 1
            elif {s[i], s[j]} == {'R', 'B'}:
                ans += g_cnt[j + 1]
                if j + dist < n and s[j + dist] == 'G':
                    ans -= 1
            else:
                ans += r_cnt[j + 1]
                if j + dist < n and s[j + dist] == 'R':
                    ans -= 1
    print(ans)


submit()

Solution (Python):


import sys
stdin = sys.stdin

def ns(): return stdin.readline().rstrip()
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))

def main():
    n = ni()
    s = ns()
    r = s.count("R")
    g = s.count("G")
    b = s.count("B")
    ans = r*g*b
    for i in range(0, n-2):
        for j in range(1, (n-1)//+1):
            if i + 2*j < n:
                if len(set([s[i], s[i+j], s[i+2*j]]))==3:
                    ans -= 1
    print(ans)

if __name__ == "__main__":
    main()