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 sys

input = sys.stdin.readline


def main():
    N = int(input())
    S = input().rstrip()

    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)

    n_R = len(R)
    n_G = len(G)
    n_B = len(B)
    ans = n_R * n_G * n_B
    if ans == 0:
        print(ans)
        exit()

    for r in R:
        for g in G:
            rg = sorted([r, g])
            dist = rg[1] - rg[0]
            if 0 <= rg[0] - dist:
                if S[rg[0] - dist] == "B":
                    ans -= 1
            if rg[1] + dist <= N - 1:
                if S[rg[1] + dist] == "B":
                    ans -= 1
            if dist % 2 == 0:
                if S[rg[0] + (dist // 2)] == "B":
                    ans -= 1
    print(ans)


if __name__ == "__main__":
    main()

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


count = 0
r_count = []
for i in range(N):
    if S[i] == "R":
        count += 1
    r_count.append(count)

count = 0
g_count = []
for i in range(N):
    if S[i] == "G":
        count += 1
    g_count.append(count)

count = 0
b_count = []
for i in range(N):
    if S[i] == "B":
        count += 1
    b_count.append(count)

ans = 0
for i in range(N):
    if S[i] == "R":
        ans += g_count[i] * (b_count[-1] - b_count[i]) + b_count[i] * (
            g_count[-1] - g_count[i]
        )
    elif S[i] == "G":
        ans += r_count[i] * (b_count[-1] - b_count[i]) + b_count[i] * (
            r_count[-1] - r_count[i]
        )
    else:
        ans += r_count[i] * (g_count[-1] - g_count[i]) + g_count[i] * (
            r_count[-1] - r_count[i]
        )

rgbs = set(("RGB", "RBG", "BRG", "BGR", "GRB", "GBR"))

for i in range(N):
    for j in range(i + 2, N, 2):
        s = S[i : j + 1 : (j - i) // 2]
        if s in rgbs:
            ans -= 1

print(ans)

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

ans=S.count("R")*S.count("G")*S.count("B")
minus=0

for i in range(0,N):
	j = 0
	while j + 2*i < N:
		if S[j] != S[j+i] and S[j+i] != S[j+2*i] and S[j] != S[j+2*i]: minus+=1
		j+=1
print(ans-minus)

Solution (Python):
N=int(input())
S=input()
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
w=0
for i in range(N-2):
	for j in range(1,int((N-i+1)/2)):
		if S[i]!=S[i+j] and S[i+j]!=S[i+j+j] and S[i]!=S[i+j+j]:
			w+=1
print((r*g*b)-w)

Solution (Python):
from collections import defaultdict
from itertools import permutations

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

pos = defaultdict(lambda: [])
for i, s in enumerate(S) :
  pos[s].append(i)

ret = 0
for a, b, c in (permutations('RGB')) :
  for center in pos[b] :
    cnt = [0] * (N + 1)
    left, right = 0, 0
    for l in pos[a] :
      if l >= center :
        break
      cnt[center-l] += 1
      left += 1
    for r in pos[c][::-1] :
      if r <= center :
        break
      cnt[r-center] += 1
      right += 1
    ret += left * right - cnt.count(2)
     

  
print(ret)

Solution (Python):
n = int(input())
s = input()
R,G,B = [0],[0],[0]
r,g,b = 0,0,0
ans = 0
for i in s[::-1]:
    if i == "R":
        r += 1
    elif i == "G":
        g += 1
    else:
        b += 1
    R.append(r)
    G.append(g)
    B.append(b)
R.reverse()
G.reverse()
B.reverse()
for ki,i in enumerate(s):
    for kj,j in enumerate(s[ki+1:],ki+1):
        INDEX = 2 * kj - ki
        if i == j:
            continue
        if i != "R" and j != "R":
            mini_ans = R[kj+1]
            if INDEX < n and s[INDEX] == "R":
                mini_ans -= 1
            ans += mini_ans
        elif i != "G" and j != "G":
            mini_ans = G[kj+1]
            if INDEX < n and s[INDEX] == "G":
                mini_ans -= 1
            ans += mini_ans
        elif i != "B" and j != "B":
            mini_ans = B[kj+1]
            if INDEX < n and s[INDEX] == "B":
                mini_ans -= 1
            ans += mini_ans
print(ans)

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

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

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

from itertools import accumulate

R = [0] + list(accumulate(R))
G = [0] +list(accumulate(G))
B = [0] + list(accumulate(B))

ans = 0
for i in range(N):
    for j in range(i + 1, N - 1):
        if S[i] == S[j]: continue
        tmp = set(["R","G","B"])
        tmp.remove(S[i])
        tmp.remove(S[j])
        Sk = tmp.pop()
        no = j + (j - i)
        if Sk == "R":
            ans += R[min(N, no)] - R[j] + R[N] - R[min(N, no + 1)]
        elif Sk == "G":
            ans += G[min(N, no)] - G[j] + G[N] - G[min(N, no + 1)]
        else:
            ans += B[min(N, no)] - B[j] + B[N] - B[min(N, no + 1)]

print(ans)

Solution (Python):
n = int(input())
s = input()
r, b, g = 0, 0, 0
for c in s:
  if c == 'R':
    r += 1
  elif c == 'G':
    b += 1
  elif c == 'B':
    g += 1
  else:
    raise ValueError
count = r * b * g
for i in range(n-2):
  s_i = s[i]
  for j in range(i+1, n-1):
    k = j + j - i
    if k < n and s_i != s[j] and s_i != s[k] and s[j] != s[k]:
      count -= 1
print(count)

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

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)
        
b = set(b)

ans = 0        

for ri in r:
    for gi in g:
        add = len(b)
        if ri - abs(gi-ri) in b:
            add -= 1
        if ri + abs(gi-ri) in b:
            add -= 1
        if gi - abs(gi-ri) in b:
            add -= 1
        if gi + abs(gi-ri) in b:
            add -= 1
        if abs(gi-ri) % 2 == 0:
            if min(ri,gi) + abs(gi-ri)//2 in b:
                add -= 1
        
        ans += max(0, add)
        
print(ans)

Solution (Python):
N = int(input())
S = input()
r = list()
g = list()
b = list()
for i in range(N):
  if(S[i] == 'R'):
    r.append(i)
  elif(S[i] == 'G'):
    g.append(i)
  else:
    b.append(i)
ans = len(r) * len(g) * len(b)
for i in range(1, N//2 +1):
  j = 0
  while(j + 2*i < N):
    A = [S[j], S[j+i], S[j+i+i]]
    if ('R' in A) and ('G' in A) and ('B' in A):
      ans -= 1
    j += 1
print(ans)

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

RD={}
GD={}
BD={}
RL=[]
GL=[]
BL=[]
for i in range(N):
    if S[i]=="R":
        RD[i]=1
        RL.append(i)
    elif S[i]=="G":
        GD[i]=1
        GL.append(i)
    else:
        BD[i]=1
        BL.append(i)



import bisect

ans=0
for i in range(1,N-1):
    if S[i]=="R":
        cnt=0
        cnt+=bisect.bisect_left(GL,i)*(len(BL)- bisect.bisect_left(BL,i))
        cnt+=bisect.bisect_left(BL,i)*(len(GL)- bisect.bisect_left(GL,i))
        hiku=0
        for j in range(i):
            if len(GL)==j or GL[j]>i:
                break
            if 2*i-GL[j] in BD:
                hiku+=1
        for j in range(i):
            if len(BL)==j or BL[j]>i:
                break
            if 2*i-BL[j] in GD:
                hiku+=1
        ans+=(cnt-hiku)
    elif S[i]=="G":
        cnt=0
        cnt+=bisect.bisect_left(RL,i)*(len(BL)-bisect.bisect_left(BL,i))
        
        cnt+=bisect.bisect_left(BL,i)*(len(RL)-bisect.bisect_left(RL,i))
        
        hiku=0
        for j in range(i):
            if len(RL)==j or RL[j]>i:
                break
            if 2*i-RL[j] in BD:
                hiku+=1
        for j in range(i):
            if len(BL)==j or BL[j]>i:
                break
            if 2*i-BL[j] in RD:
                hiku+=1
        ans+=(cnt-hiku)
    else:
        cnt=0
        cnt+=bisect.bisect_left(RL,i)*(len(GL)- bisect.bisect_left(GL,i))
        cnt+=bisect.bisect_left(GL,i)*(len(RL)- bisect.bisect_left(RL,i))
        hiku=0
        for j in range(i):
            if len(RL)==j or RL[j]>i:
                break
            if 2*i-RL[j] in GD:
                hiku+=1
        for j in range(i):
            if len(GL)==j or GL[j]>i:
                break
            if 2*i-GL[j] in RD:
                hiku+=1
        ans+=(cnt-hiku)
    
print(ans)

Solution (Python):
import itertools
n = int(input())
s = input()
rui_rl = [0] + list(itertools.accumulate([1 if x == 'R' else 0 for x in s]))
rui_gl = [0] + list(itertools.accumulate([1 if x == 'G' else 0 for x in s]))
rui_bl = [0] + list(itertools.accumulate([1 if x == 'B' else 0 for x in s]))
rui = {'R': rui_rl, 'G': rui_gl, 'B': rui_bl}
ans = 0
for i in range(n):
    for j in range(i+1, n):
        if s[i] == s[j]:
            continue

        if 'R' not in [s[i], s[j]]:
            target = 'R'
        elif 'G' not in [s[i], s[j]]:
            target = 'G'
        else:
            target = 'B'

        dif_ji = j-i

        ans += rui[target][-1] - rui[target][j+1]
        if j+dif_ji <= n-1:
            if s[j+dif_ji] == target:
                ans -= 1
print(ans)

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

ans=0
for i in range(n-2):
    if (s[i]=="R"):
        numG=s[i+1:].count("G")
        numB=s[i+1:].count("B")
        ans+=numG*numB
        for j in range(i+1,(n+1+i)//2):
            
            if (s[j]!=s[j+(j-i)] and s[j]!="R" and s[2*j-i]!="R"):
                ans-=1
                
    elif (s[i]=="G"):
        numG=s[i+1:].count("R")
        numB=s[i+1:].count("B")
        ans+=numG*numB
        for j in range(i+1,(n+1+i)//2):
            if (s[j]!=s[j+(j-i)] and s[j]!="G" and s[2*j-i]!="G"):
                ans-=1
        
    else:
        numG=s[i+1:].count("R")
        numB=s[i+1:].count("G")
        ans+=numG*numB
        for j in range(i+1,(n+1+i)//2):
            if (s[j]!=s[j+(j-i)] and s[j]!="B" and s[2*j-i]!="B"):
                ans-=1

print(ans)

Solution (Python):
N = int(input())
R = []
G = []
B = []
s =input()
ans = 0
for i in range(N):
    if s[i] == "R":
        R.append(i)
    elif s[i] == "G":
        G.append(i)
    else:
        B.append(i)
sB = set(B)
ans = len(R) * len(G) * len(B)
for r in R:
    for g in G:
        i = min(r,g)
        j = max(r,g)
        sa = j - i
        if i - sa in sB:
            ans -= 1
        if j + sa in sB:
            ans -= 1
        if (i + j) / 2 in sB:
            ans -= 1
print(ans)

Solution (Python):
import copy
n = int(input())
s = input()
total = 0
rgb = {'R', 'G', 'B'}
rgb_count = {key:s.count(key) for key in rgb}

for i in range(n):
    a = s[i]
    rgb_count[a] -= 1
    rgb_copy = copy.copy(rgb_count)
    for j in range(i+1, n):
        rgb_copy[s[j]] -= 1
        if s[j] != a:
            b = s[j]
            remain = rgb - {a, b}
            c = [i for i in remain][0]
            total += rgb_copy[c]
            if 2*j-i < n and s[2*j-i] == c:
                total -= 1

print(total)

Solution (Python):

import re
import math
import itertools
from copy import deepcopy
import random
from heapq import heappop,heappush
import time
import os
import queue
import sys
import datetime
from functools import lru_cache
readline=sys.stdin.readline
sys.setrecursionlimit(2000)

alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def is_power(a,b):
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def bin_(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def fac_list(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:
        return num
def get_primes(n,type="int"):
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=2):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=" "):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def floor_(n,x=1):
    return x*(n//x)
def ceil_(n,x=1):
    return x*((n+x-1)//x)


import re
import math
import itertools
from copy import deepcopy
import random
from heapq import heappop,heappush
import time
import os
import queue
import sys
import datetime
from functools import lru_cache
readline=sys.stdin.readline
sys.setrecursionlimit(2000)

alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def is_power(a,b):
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def bin_(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def fac_list(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:
        return num
def get_primes(n,type="int"):
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=2):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=" "):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def floor_(n,x=1):
    return x*(n//x)
def ceil_(n,x=1):
    return x*((n+x-1)//x)

n=int(input())
s=input()
R=s.count("R")
G=s.count("G")
B=s.count("B")

ans=R*G*B
for a in range(1,n):
    for b in range(0,n):
        if(b>=n or b+a>=n or b+a+a>=n):continue
        if s[b]!=s[b+a] and s[b+a]!=s[b+a+a] and s[b+a+a]!=s[b]:
            ans-=1
print(ans)

Solution (Python):



ans = r = g = b = rg = gb = br = 0

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

for ch in s:
    if ch == 'R':
        r += 1
        br += b
        rg += g
        ans += gb

    if ch == 'B':
        b += 1
        br += r
        gb += g
        ans += rg

    if ch == 'G':
        g += 1
        rg += r
        gb += b
        ans += br

c = 0

for i in range(1, n // 2 + 1):
    for j in range(0, n - 1):

        if j + 2 * i >= n:
            break

        ch1 = s[j]
        ch2 = s[j + i]
        ch3 = s[j + 2 * i]

        if len({ch1, ch2, ch3}) == 3:
            c += 1

print (ans - c)

Solution (Python):
n = int(input())
s = input()
import collections
temp1 = 0
for j in range(1,n-1):
    i,k = j-1,j+1
    while i >= 0 and k < n:
        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            temp1 += 1
        i,k = i-1,k+1
c = collections.Counter(s)
temp2 = 1
for key in "RGB":
    temp2 *= c[key]
print(temp2-temp1)

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

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

ans = r*g*b

for i in range(1, n//2+1):
    for j in range(n):
        if j+2*i < n:
            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)

Solution (Python):
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))



N = I()
S = str(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
for r in R:
    for g in G:
        ans += len(B)
        mi,ma = min(r,g),max(r,g)
        p = bisect_left(B,2*ma-mi)
        if 0<= p <= len(B)-1 and B[p] == 2*ma-mi and 2*ma-mi > ma:
            ans -= 1
        p = bisect_left(B,(ma+mi)/2)
        if 0<= p <= len(B)-1 and B[p] == (ma+mi)/2 and mi<B[p]<ma:
            ans -= 1
        p = bisect_left(B,2*mi-ma)
        if 0 <= p <= len(B)-1 and B[p] == 2*mi-ma and B[p]<mi:
            ans -= 1
print(ans)

Solution (Python):

''':'
docker run --rm -it -v $(cd $(dirname $0) && pwd):/vo:ro pypy:3-2.4.0 \
   /bin/bash -c "pypy3 /vo/$(basename $0) < /vo/input.txt"
exit $?
'''
import sys


def _s(): return sys.stdin.readline().strip()


def _i(): return int(sys.stdin.readline().strip())


def main():
    n = _i()
    s = _s()
    c = {
        "R": [0] * (n + 1),
        "G": [0] * (n + 1),
        "B": [0] * (n + 1)
    }
    j = n
    for rgb in reversed(s):
        j -= 1
        for _rgb in "RGB":
            c[_rgb][j] = c[_rgb][j+1]
        c[rgb][j] += 1

    ans = 0
    rgb = {"R", "G", "B"}
    for i in range(n-2):
        c1 = s[i]
        for j in range(i+1, n-1):
            c2 = s[j]
            if c1 == c2:
                continue
            
            c3 = (rgb - {c1, c2}).pop()
            ans += c[c3][j+1]
            k = 2 * j - i
            if k < n and s[k] == c3:
                ans -= 1
    return ans


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

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

S = S.replace('R', '0')
S = S.replace('G', '1')
S = S.replace('B', '2')
lis = [[0, 0, 0] for _ in range(N)]
index_lis = [0, 2, 1, 0]
for i in range(N):
  j = N-1-i
  for k in range(j):
    lis[k][int(S[j])] += 1


count = 0
for i in range(N-2):
  for j in range(i+1, N-1):
    if S[i] != S[j]:
      if 2*j-i < N:
        if S[2*j-i] == S[i] or S[2*j-i] == S[j]:
          count += lis[j][index_lis[int(S[i])+int(S[j])]]
        else:
          count += lis[j][int(S[2*j-i])] - 1
      else:
        count += lis[j][index_lis[int(S[i])+int(S[j])]]
print(count)

Solution (Python):
n=int(input())
s=input()
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
answer=r*g*b
for j in range(1,int(n/2)+1):
    for k in range(0,n-2*j):
        if s[k]!=s[k+j] and s[k]!=s[k+2*j] and s[k+j]!=s[k+2*j]:
            answer-=1
print(answer)

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

d = {
    'R': list(),
    'G': list(),
    'B': list()
}


for i, c in enumerate(S):
    d[c].append(i+1)

all = len(d['R']) * len(d['G']) * len(d['B'])

for c in 'RGB':
    d[c] = sorted(d[c])



for c in 'RGB':
    s = set([2 * x for x in d[c]])
    cs = [x for x in 'RGB' if x != c]

    for i in d[cs[0]]:
        for j in d[cs[1]]:
            if (i+j) in s:
                all -= 1

print(all)

Solution (Python):
N=int(input())
S=input()
ans = 0
d={'R':0,'G':0,'B':0}
R,G,B=[],[],[]
for i in S:
    d[i]+=1
    R.append(d['R'])
    G.append(d['G'])
    B.append(d['B'])
for i in range(N-2):
    for j in range(i+1,N-1):
        s = [S[i],S[j]]
        if len(set(s))==2:
            if 'R' not in s:
                ans += R[-1]-R[j]
            elif 'G' not in s:
                ans += G[-1]-G[j]
            else:
                ans += B[-1]-B[j]
            if 0<=2*j-i<N and len(set([S[i],S[j],S[2*j-i]]))==3:
                ans -=1
print(ans)

Solution (Python):
from sys import stdin
import bisect
def main():
    
    readline=stdin.readline
    N=int(readline())
    S=readline().strip()

    res=0

    R=[]
    G=[]
    B=[]
    flags=[""]*N
    for i in range(N):
        if S[i]=="R":
            R.append(i)
            flags[i]="R"
        elif S[i]=="G":
            G.append(i)
            flags[i]="G"
        else:
            B.append(i)
            flags[i]="B"
    
    
    for i in range(len(R)):
        for j in range(len(G)):
            n=max(R[i],G[j])
            k=bisect.bisect_left(B,n)
            res+=len(B)-k
            if n+n-min(R[i],G[j])<N:
                if flags[n+n-min(R[i],G[j])]=="B":
                    res-=1
    
    for i in range(len(R)):
        for j in range(len(B)):
            n=max(R[i],B[j])
            k=bisect.bisect_left(G,n)
            res+=len(G)-k
            if n+n-min(R[i],B[j])<N:
                if flags[n+n-min(R[i],B[j])]=="G":
                    res-=1

    for i in range(len(B)):
        for j in range(len(G)):
            n=max(B[i],G[j])
            k=bisect.bisect_left(R,n)
            res+=len(R)-k
            if n+n-min(B[i],G[j])<N:
                if flags[n+n-min(B[i],G[j])]=="R":
                    res-=1

    print(res)
if __name__=="__main__":
    main()

Solution (Python):
def main():
    n=int(input())
    S=tuple(input().strip())
    r,g,b=0,0,0
    for s in S:
        if s=='R':
            r+=1
        elif s=='G':
            g+=1
        else:
            b+=1
    ans=r*g*b
    
    for i in range(n-2):
        for j in range(i+1,n-1):
            k=i+(j-i)*2
            if k>=n:
                break
            
            
            if S[i]!=S[j] and S[j]!=S[k] and S[k]!=S[i]:
                
                ans-=1
    print(ans)
    
if __name__=='__main__':
    main()

Solution (Python):
import bisect

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

dic = {}
dic['R'] = []
dic['G'] = []
dic['B'] = []

for i in range(n):
    dic[s[i]].append(i)

rem = {}

rem['G'] = ['R', 'B']
rem['B'] = ['R','G']
rem['R'] = ['B', 'G']

res=0

for i in range(n):
    neigh1 = rem[s[i]][0]
    neigh2 = rem[s[i]][1]
    ind = bisect.bisect_right(dic[neigh1],i)
    for j in range(ind, len(dic[neigh1])):
        node = dic[neigh1][j]
        nind = bisect.bisect_right(dic[neigh2],node)

        l = max(0,len(dic[neigh2])-nind)

        diff = node-i
        if node+diff>=nind and node+diff<n and s[node+diff]==neigh2:
            l-=1

        res+=l

    ind = bisect.bisect_right(dic[neigh2],i)
    for j in range(ind, len(dic[neigh2])):
        node = dic[neigh2][j]
        nind = bisect.bisect_right(dic[neigh1],node)

        l = max(0,len(dic[neigh1])-nind)

        diff = node-i
        if node+diff>=nind and node+diff<n and s[node+diff]==neigh1:
            l-=1

        res+=l

print(res)

Solution (Python):

import sys
import math
import string
import collections
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
import bisect

MOD = 10 ** 9 + 7
INF = float('inf')
input = lambda: sys.stdin.readline().strip()

sys.setrecursionlimit(10 ** 8)

N = int(input())
K = list(input())
a = collections.Counter(K)
ans = 0
R = list(itertools.accumulate([1 if K[i] == "R" else 0 for i in range(N)])) + [0]
G = list(itertools.accumulate([1 if i == "G" else 0 for i in K])) + [0]
B = list(itertools.accumulate([1 if i == "B" else 0 for i in K])) + [0]
for i in range(N):
    if K[i] == "R":
        ans += G[i - 1] * B[i - 1]
    elif K[i] == "G":
        ans += R[i - 1] * B[i - 1]
    else:
        ans += R[i - 1] * G[i - 1]
for k in range(2, N):
    for i in range(0, k):
        j = (k + i) / 2
        if j == (k + i) // 2 and j > i:
            j = int(j)
            if K[k] != K[i] and K[k] != K[j] and K[i] != K[j]:
                ans -= 1
print(ans)

Solution (Python):
n=int(input())
s=input()
x=(s.count('R'))*(s.count('G'))*(s.count('B'))
for i in range(1,(n-1)//2+1):
  for j in range(n-i*2):
    if len(set([s[j],s[j+i],s[j+i+i]]))==3:
      x-=1
print(x)

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

accum=[]
num_r=num_g=num_b=0
for i in range(N):
  if S[i]=="R":
    num_r+=1
  elif S[i]=="G":
    num_g+=1
  else:
    num_b+=1
  accum.append((num_r,num_g,num_b))

dp=[0]*N
for i in range(3,N):
  dp[i]=dp[i-1]
  nr,ng,nb=accum[i-1]
  if S[i]=="R":
    dp[i]+=ng*nb
  elif S[i]=="G":
    dp[i]+=nr*nb
  else:
    dp[i]+=ng*nr
    
  for j in range(1,i//2+1):
    
    set_rgb=set()
    set_rgb.add(S[i])
    set_rgb.add(S[i-j])
    set_rgb.add(S[i-2*j])
    if len(set_rgb)==3:
      dp[i]-=1
      
print(dp[-1])

Solution (Python):
import bisect

def brute():
    N=int(input())
    S=input()

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

    ans=0
    for i,c in enumerate(S):
        if c=="R":
            R.append(i)
        elif c=="B":
            B.append(i)
        else:
            G.append(i)

    for mid in range(1,N-1):
        if S[mid]=="R":
            low_1=bisect.bisect_left(G,mid)
            low_2 =bisect.bisect_left(B,mid)
            high_1=len(G)-low_1
            high_2=len(B)-low_2
        elif S[mid]=="B":
            low_1=bisect.bisect_left(G,mid)
            low_2 =bisect.bisect_left(R,mid)
            high_1=len(G)-low_1
            high_2=len(R)-low_2
        else:
            low_1=bisect.bisect_left(B,mid)
            low_2 =bisect.bisect_left(R,mid)
            high_1=len(B)-low_1
            high_2=len(R)-low_2

        dup = sum([1 if a!=b and a!=S[mid] and b!=S[mid]else 0 for a,b in zip(reversed(S[:mid]),S[mid+1:])])
        t = low_1*high_2 + low_2*high_1
        ans+=t
        ans -= dup
    print(ans)

brute()

Solution (Python):
import sys
input = sys.stdin.readline
LOCAL = len(sys.argv) > 1 and sys.argv[1] == 'LOCAL'


def dprint(*args):
  if LOCAL:
    print(*args)


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

rs, gs, bs = [], [], []
for l, c in enumerate(s):
  if c == 'R':
    rs.append(l)
  if c == 'G':
    gs.append(l)
  if c == 'B':
    bs.append(l)
sbs = set(bs)

ans = 0
for r in rs:
  for g in gs:
    m = min(r, g)
    M = max(r, g)
    notbs = [m - (M - m), M + (M - m)]
    if (M + m) % 2 == 0:
      notbs.append((M + m) // 2)
    
    dprint(m, M, notbs, sbs)
    
    

    a = len(sbs)
    for notb in notbs:
      if notb in sbs:
        a -= 1
    if a > 0:
      ans += a


print(ans)

Solution (Python):

import sys
import math


n = int(input())


s=input()

num_R=0
num_G=0
num_B=0

for i in range(n):
	if(s[i]=="R"):
		num_R+=1
	if(s[i]=="G"):
		num_G+=1
	if(s[i]=="B"):
		num_B+=1
total=num_R*num_G*num_B



tmp=n//2

for i in range(1,tmp+1):
	for j in range(n-i*2):
		if(s[j]!=s[j+i] and s[j]!=s[j+i*2] and s[j+i]!=s[j+i*2]):
			total-=1


print(total)