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):
mod = 10**9 + 7
mod2 = 2**61 + 1
int1 = lambda x: int(x) - 1
from collections import deque
import heapq
import time
from bisect import bisect_left, insort_left, bisect_right
import sys
import random
import itertools



def input():
    return sys.stdin.readline().strip("\n").strip(" ")


_NUMINT_ALL = list(range(10))
_START_TIME = time.time()
INDEX_KETA = 10**12
INF = 9223372036854775807  

def main():
    ans = solve()

    if ans is True or ans is False:
        YesNo(ans)
    elif ans is None:
        return

    if isinstance(ans, tuple):
        split_print_space(ans)
    else:
        print(ans)


def solve():

    N = iip()
    A = iip()

    B = []
    for i in A:
        if i == "R":
            B.append(0)
        elif i == "G":
            B.append(1)
        elif i == "B":
            B.append(2)

    

    C = []
    n = [0, 0, 0]
    for i in B:
        n[i] += 1
        C.append([i for i in n])

    

    ans = 0
    for i in range(N-2):
        for j in range(i+1, N-1):
            if B[i] == B[j]:
                continue

            cur = sum(C[-1]) - C[-1][B[i]] - C[-1][B[j]] 
            cur -= sum(C[j]) - C[j][B[i]] - C[j][B[j]]

            idx = j + (j-i)
            if idx < N and B[idx] != B[i] and B[idx] != B[j]:
                cur -= 1
            ans += cur

            

    print(ans)





def kiriage_warizan(a, b):
    return -(-a // b)


def iip(listed=False):  
    d = input().rstrip("\n").split()
    try:
        ret = [int(i) for i in d]
    except:
        ret = [int(i) if i in _NUMINT_ALL else i for i in d]
        if len(ret) == 1 and listed is False:
            return ret[0]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def iipt(l, listed=True):  
    if isinstance(l, list):
        l = l[0]  
    assert isinstance(l, int)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed))
    return ret


def saidai_kouyakusuu(A):  
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m


def flatten(l):
    return list(itertools.chain.from_iterable(l))


def index_sorted(sorted_list, target):
    idx = bisect_left(sorted_list, target)
    if idx != len(sorted_list) and sorted_list[idx] == target:
        return idx
    else:
        return False


def time_debug_10percent():
    a = random.randint(0, 9)
    if a == 9:
        sys.exit()


def time_debug(t):
    time.sleep(_START_TIME + t - time.time())
    sys.exit()


def make_graph_edge_flat(N):  
    ret = []
    for i in range(N - 1):
        a, b, c = iip()
        a -= 1
        b -= 1
        ret[a].append((b, c))
        ret[b].append((a, c))
    return ret


def sort_tuples(l, index):  
    if isinstance(l, list):
        l.sort(key=lambda x:x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x:x[index])


def count_elements(l):  
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  
    if index >= len(l):  
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def sortstr(s):  
    return "".join(sorted(s))


def iip_ord(startcode="a"):  
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  
    if isinstance(s, int):
        print(s)
        return
    keta = max([len(str(i)) for i in itertools.chain.from_iterable(s)])
    print("--------")
    for i in s:
        print([str(j).rjust(keta) for j in i])
    print("--------")


def bitall(N):  
    ret = []
    for i in range(2**N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret


def split_print_space(s):  
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  
    ret = []
    for i in range(2, int(n**0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        
        pass
    return ret


def inv(n, mod):  
    return power(n, mod - 2)


def power(n, p, mod_=mod):  
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_)**2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


def nibutan_func(func, target, left, right, side="left", seido=1):  
    l = left
    r = right
    if seido == 1:
        x = (l + r) // 2
    else:
        x = (l + r) / 2
    while r - l > seido:
        
        if seido == 1:
            x = (l + r) // 2
        else:
            x = (l + r) / 2
        if func(x) == target:
            if side == "left":
                r = x
            else:
                l = x


        elif func(x) > target:
            r = x
        else:
            
            l = x

    
    if side == "left" and func(r) == target:
        return r
    elif side != "left" and func(l) == target:
        return l
    elif side == "left":
        return l
    else:
        return r


def nibutan_list(list_, target, side="left"):  
    if not isinstance(list_, list):
        list_ = list(list_)

    l = 0
    r = len(list_)
    x = (l + r) // 2
    while r - l > 1:
        x = (l + r) // 2
        if list_[x] == target:
            return x
        elif list_[x] > target:
            r = x
        else:
            l = x

    if side == "left" or list_[x] == target:
        return l
    else:
        return r


class UfTree():
    def __init__(self, maxnum):
        self.parent = list(range(maxnum))
        self._size = [1] * maxnum
        self.rank = [0] * maxnum

    def size(self, a):
        return self._size[self.root(a)]

    def root(self, a):
        rank = 0
        cur = a
        while True:
            if self.parent[cur] == cur:
                
                
                return cur
            else:
                self.parent[cur] = self.parent[self.parent[cur]]
                cur = self.parent[cur]
                rank += 1

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return self

        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        return self


if __name__ == "__main__":
    main()

Solution (Python):
import os
from collections import Counter

import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


N = int(sys.stdin.buffer.readline())
S = sys.stdin.buffer.readline().decode().rstrip()

eq = 0
nb = 0
l, m, r = 0, 1, 2
for w in range(1, N):
    l = 0
    m = l + w
    r = m + w
    while r < N:
        eq += S[l] == S[m] or S[m] == S[r] or S[r] == S[l]
        nb += 1
        l += 1
        m += 1
        r += 1
rgb = Counter(S)
na = 0
na += (N - rgb['R']) * (rgb['R'] * (rgb['R'] - 1) // 2)
na += (N - rgb['G']) * (rgb['G'] * (rgb['G'] - 1) // 2)
na += (N - rgb['B']) * (rgb['B'] * (rgb['B'] - 1) // 2)
na += (rgb['R'] - 1) * (rgb['R'] - 2) * rgb['R'] // 6
na += (rgb['B'] - 1) * (rgb['B'] - 2) * rgb['B'] // 6
na += (rgb['G'] - 1) * (rgb['G'] - 2) * rgb['G'] // 6

total = N * (N - 1) * (N - 2) // 6
print(total - na - nb + eq)

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

dicts = {'R':0, 'G':0, 'B':0}
for i in s:
    dicts[i] += 1

ans = dicts['R'] * dicts['G'] * dicts['B']

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

print(ans)

Solution (Python):
n = int(input())
s = input()
rl = s.count('R')
gl = s.count('G')
bl = s.count('B')
rr = 0
gr = 0
br = 0
if s[0] == 'R':
    rl -= 1
    rr += 1
elif s[0] == 'G':
    gl -= 1
    gr += 1
else:
    bl -= 1
    br += 1

ans = 0
for i in range(1, n-1):
    for j in range(1, n//2+1):
        if i-j < 0 or i+j > n-1:
            break
        if s[i+j] != s[i-j] and s[i+j] != s[i] and s[i-j] != s[i]:
            ans -= 1
    if s[i] == 'R':
        ans += bl*gr + br*gl
        rl -= 1
        rr += 1
    elif s[i] == 'G':
        ans += rr*bl + rl*br
        gl -= 1
        gr += 1
    else:
        ans += gr*rl + gl*rr
        bl -= 1
        br += 1
print(ans)

Solution (Python):

table = { "R": 0, "G": 1, "B": 2 }

N = int(input())
S = [table[c] for c in input().strip()]

counts = [0, 0, 0]

for c in S:
	counts[c] += 1

count_diff = counts[0] * counts[1] * counts[2]

count_diff_si = 0
for i in range(0, N - 2):
	ci = S[i]
	for j in range(i + 1, N - 1):
		k = j + j - i
		if k >= N:
			break
		cj = S[j]
		ck = S[k]
		if ci != cj and ci != ck and cj != ck:
			count_diff_si += 1
print(count_diff - count_diff_si)

Solution (Python):
from collections import defaultdict

def main():
    N = int(input())
    S = list(input())
    d = []
    c = [0,0,0]
    R = 0
    G = 0
    B = 0
    for i in range(N-1,-1,-1):
        if S[i] == 'R':
            R += 1
        if S[i] == 'G':
            G += 1
        if S[i] == 'B':
            B += 1
        d.append([R,G,B])
            
    d.reverse()
    ans = 0
    for i in range(N):
        if S[i] == 'R':
            ans += d[i][1] * d[i][2]
        if S[i] == 'G':
            ans += d[i][0] * d[i][2]
        if S[i] == 'B':
            ans += d[i][0] * d[i][1]
        for k in range(N):
            if i + 2 * k >= N:
                break
            if S[i] == 'R':
                if S[i + k] == 'G' and S[i + 2 * k] == 'B':
                    ans -= 1
                if S[i + k] == 'B' and S[i + 2 * k] == 'G':
                    ans -= 1 
            if S[i] == 'G':
                if S[i + k] == 'R' and S[i + 2 * k] == 'B':
                    ans -= 1
                if S[i + k] == 'B' and S[i + 2 * k] == 'R':
                    ans -= 1 
            if S[i] == 'B':
                if S[i + k] == 'R' and S[i + 2 * k] == 'G':
                    ans -= 1
                if S[i + k] == 'G' and S[i + 2 * k] == 'R':
                    ans -= 1 

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

Solution (Python):
n = int(input())
s = input()
rl = s.count('R')
gl = s.count('G')
bl = s.count('B')
rr = 0
gr = 0
br = 0
if s[0] == 'R':
    rl -= 1
    rr += 1
elif s[0] == 'G':
    gl -= 1
    gr += 1
else:
    bl -= 1
    br += 1

ans = 0
for i in range(1, n-1):
    for j in range(1, n//2+1):
        if i-j < 0 or i+j > n-1:
            break
        if s[i+j] != s[i-j] and s[i+j] != s[i] and s[i-j] != s[i]:
            ans -= 1
    if s[i] == 'R':
        ans += bl*gr + br*gl
        rl -= 1
        rr += 1
    elif s[i] == 'G':
        ans += rr*bl + rl*br
        gl -= 1
        gr += 1
    else:
        ans += gr*rl + gl*rr
        bl -= 1
        br += 1
print(ans)

Solution (Python):
N = int(input())
S = input()
color = [[0 for _ in range(3)] for _ in range(N+1)]
for i, c in enumerate(S):
    for j in range(3):
        color[i+1][j] = color[i][j]
    if c == "R":
        color[i+1][0] += 1
    elif c == "G":
        color[i+1][1] += 1
    elif c == "B":
        color[i+1][2] += 1

rn = color[N][0]
gn = color[N][1]
bn = color[N][2]

ans = 0
for i, c in enumerate(S):
    if i == 0 or i == N-1:
        continue
    j = 1
    while i-j >=0 and i+j <=N-1:
        if S[i-j] != S[i] and S[i] != S[i+j] and S[i-j] != S[i+j]:
            ans -= 1
        j += 1
    if c == "R":
        ans += color[i][1] * (bn - color[i+1][2])
        ans += color[i][2] * (gn - color[i+1][1])
    elif c == "G":
        ans += color[i][0] * (bn - color[i+1][2])
        ans += color[i][2] * (rn - color[i+1][0])
    elif c == "B":
        ans += color[i][0] * (gn - color[i+1][1])
        ans += color[i][1] * (rn - color[i+1][0])
print(ans)

Solution (Python):
import itertools
import bisect

N = int(input())
S = input()
R_set = set()
G_set = set()
B_set = set()
R = []
G = []
B = []
R_ids = [0] * N
G_ids = [0] * N
B_ids = [0] * N

for i, s in enumerate(S):
    if s == 'R':
        R_set.add(i)
        R.append(i)
        R_ids[i] = 1
    elif s == 'G':
        G_set.add(i)
        G.append(i)
        G_ids[i] = 1
    else:
        B_set.add(i)
        B.append(i)
        B_ids[i] = 1


R_ids = list(itertools.accumulate(reversed(R_ids)))[::-1]
G_ids = list(itertools.accumulate(reversed(G_ids)))[::-1]
B_ids = list(itertools.accumulate(reversed(B_ids)))[::-1]

ans = 0
for r_idx in R:
    start = bisect.bisect_left(G, r_idx)
    for g_idx in G[start:]:
        diff = g_idx - r_idx
        num = B_ids[g_idx]
        if g_idx+diff in B_set:
            num -= 1
        ans += num
    
    start = bisect.bisect_left(B, r_idx)
    for b_idx in B[start:]:
        diff = b_idx - r_idx
        num = G_ids[b_idx]
        if b_idx+diff in G_set:
            num -= 1
        ans += num

for g_idx in G:
    start = bisect.bisect_left(R, g_idx)
    for r_idx in R[start:]:
        diff = r_idx - g_idx
        num = B_ids[r_idx]
        if r_idx+diff in B_set:
            num -= 1
        ans += num
    
    start = bisect.bisect_left(B, g_idx)
    for b_idx in B[start:]:
        diff = b_idx - g_idx
        num = R_ids[b_idx]
        if b_idx+diff in R_set:
            num -= 1
        ans += num

for b_idx in B:
    start = bisect.bisect_left(G, b_idx)
    for g_idx in G[start:]:
        diff = g_idx - b_idx
        num = R_ids[g_idx]
        if g_idx+diff in R_set:
            num -= 1
        ans += num
    
    start = bisect.bisect_left(R, b_idx)
    for r_idx in R[start:]:
        diff = r_idx - b_idx
        num = G_ids[r_idx]
        if r_idx+diff in G_set:
            num -= 1
        ans += num


print(ans)

Solution (Python):
n=int(input())
s=input()
R=[0]*n
G=[0]*n
B=[0]*n
rcnt=0;gcnt=0;bcnt=0
ans=0
for i in range(n):
    if s[i]=="R":R[i]=R[i-1]+1;B[i]=B[i-1];G[i]=G[i-1];rcnt+=1
    elif s[i]=="G":G[i]=G[i-1]+1;R[i]=R[i-1];B[i]=B[i-1];gcnt+=1
    else:B[i]=B[i-1]+1;R[i]=R[i-1];G[i]=G[i-1];bcnt+=1
for i in range(n-1):
    for j in range(i+1,n):
        if s[i]==s[j]:continue
        if "R"!=s[i] and "R"!=s[j]:
            if 2*j-i>=n:
                ans+=rcnt-R[j]
            else:
                ans+=rcnt-R[j]
                if s[2*j-i]=="R":ans-=1
        elif "B"!=s[i] and "B"!=s[j]:
            if 2*j-i>=n:
                ans+=bcnt-B[j]
            else:
                ans+=bcnt-B[j]
                if s[2*j-i]=="B":ans-=1
        else:
            if 2*j-i>=n:
                ans+=gcnt-G[j]
            else:
                ans+=gcnt-G[j]
                if s[2*j-i]=="G":ans-=1
print(ans)

Solution (Python):
import sys
from itertools import combinations

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N = int(rl())
    S = input()
    
    acc = [[0] * 3 for _ in range(N + 1)]
    for i in range(1, N + 1):
        acc[i] = acc[i - 1][:]
        if S[i - 1] == 'R':
            acc[i][0] += 1
        elif S[i - 1] == 'G':
            acc[i][1] += 1
        else:
            acc[i][2] += 1
    
    ans = 0
    for i, j in combinations(range(N - 1), 2):
        si, sj = S[i], S[j]
        if si == sj:
            continue
        if 'R' not in [si, sj]:
            ans += acc[N][0] - acc[j][0]
            t = j + j - i
            if t < N:
                ans -= S[t] == 'R'
        elif 'G' not in [si, sj]:
            ans += acc[N][1] - acc[j][1]
            t = j + j - i
            if t < N:
                ans -= S[t] == 'G'
        else:
            ans += acc[N][2] - acc[j][2]
            t = j + j - i
            if t < N:
                ans -= S[t] == 'B'
    print(ans)


if __name__ == '__main__':
    solve()

Solution (Python):

from collections import defaultdict

con = 10 ** 9 + 7

def getlist():
	return list(map(int, input().split()))


def main():
	N = int(input())
	S = list(input())
	LR = [0] * (N + 1)
	LG = [0] * (N + 1)
	LB = [0] * (N + 1)
	for i in range(N):
		LR[i + 1] = LR[i]
		LG[i + 1] = LG[i]
		LB[i + 1] = LB[i]
		if S[i] == "R":
			LR[i + 1] += 1
		elif S[i] == "G":
			LG[i + 1] += 1
		else:
			LB[i + 1] += 1

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

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

	print(ans)



if __name__ == '__main__':
	main()

Solution (Python):


def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate, groupby
    
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    

    
    

    n = int(input())
    s = input().rstrip()
    res = s.count('R') * s.count('G') * s.count('B')

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

    print(res - cnt)

if __name__ == '__main__':
    main()

Solution (Python):

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

CR = [0]*N
CG = [0]*N
CB = [0]*N

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

rR = [0]*N
rG = [0]*N
rB = [0]*N

for i in range(N-1):
    I = N-i-2
    rR[I] = rR[I+1]+CR[I+1]
    rG[I] = rG[I+1]+CG[I+1]
    rB[I] = rB[I+1]+CB[I+1]
    
ans = 0
for i in range(N):
    I = i
    a = S[I]
    for j in range(N-i-1):
        J = i+j+1
        b = S[J]
        if a != b:
            add = 0
            if "R" != a and "R" != b:
                add += rR[J]
                d = J-I
                if J+d < N:
                    add -= CR[J+d] 
                
            elif "G" != a and "G" != b:
                add += rG[J]
                d = J-I
                if J+d < N:
                    add -= CG[J+d] 
            else:
                add += rB[J]
                d = J-I
                if J+d < N:
                    add -= CB[J+d] 
            ans+=add
            
            
print(ans)

Solution (Python):


import sys
from itertools import accumulate

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

N = INT()
S = input()
A = [0] * N
for i, s in enumerate(S):
    if s == 'G':
        A[i] = 1
    elif s == 'B':
        A[i] = 2

acc = list2d(3, N, 0)
for i, a in enumerate(A):
    acc[a][i] = 1
for i in range(3):
    acc[i] = list(accumulate(acc[i][::-1]))[::-1]

ans = 0
for i, a1 in enumerate(A):
    for j in range(i+1, N):
        a2 = A[j]
        if a1 == a2:
            continue
        a3 = 3 - a1 - a2
        cnt = acc[a3][j]
        dist = j - i
        if j + dist < N and A[j+dist] == a3:
            cnt -= 1
        ans += cnt
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
yo = input()
if(yo[-1]=='\n'):
	yo=yo[:-1]
n=int(yo)
s=input()
if(s[-1]=='\n'):
	s=s[:-1]
preb=[0 for i in range(n)]
preg=[0 for i in range(n)]
prer=[0 for i in range(n)]
b=0; g=0; r=0
for i in range(n-1,-1,-1):
	if(s[i]=='R'):
		r+=1
	elif(s[i]=='G'):
		g+=1
	else:
		b+=1
	preb[i]=b; prer[i]=r; preg[i]=g



l=[prer,preg,preb]
s=s.replace('R','0')
s=s.replace('G','1')
s=s.replace('B','2')
ans=0

for i in range(n):
	for j in range(i+1,n):
		if(s[i]!=s[j]):
			if(j+1>=n):
				continue
			ct = l[(3-int(s[i])-int(s[j]))][j+1]
			diff = j-i
			if((j+diff)<n and s[j+diff]==str(3-int(s[i])-int(s[j]))):
				ct-=1
			ans+=ct
print(ans)

Solution (Python):
def main():
    n = int(input())
    s = input().rstrip()
    ans = 0
    a = [[0]*3 for _ in range(n)]
    rgb = [None]*n
    for i in range(n):
        if s[i] == "R":
            rgb[i] = 0
        elif s[i] == "G":
            rgb[i] = 1
        else:
            rgb[i] = 2
    a[n-1][rgb[n-1]] += 1
    for i in reversed(range(n-1)):
        a[i][rgb[i]] += 1
        for j in range(3):
            a[i][j] += a[i+1][j]
    for i in range(n-2):
        for j in range(i+1, n-1):
            if rgb[i] == rgb[j]:
                continue
            x = 3 - rgb[i] - rgb[j]
            L = j + (j - i)
            ans += a[j+1][x]
            if L < n and rgb[L] == x:
                ans -= 1
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
import sys
readline = sys.stdin.readline

N = int(readline())
S = readline().rstrip()

R, G, B = 'R', 'G', 'B'

nr, ng, nb = (S.count(v) for v in (R, G, B))

ans = nr * ng * nb

for w in range(1, N // 2 + 1):
    for i in range(N):
        if i + 2*w >= N:
            break
        if S[i] != S[i + w] and S[i + w] != S[i + 2*w] and S[i + 2*w] != S[i]:
            ans -= 1

print(ans)

Solution (Python):
MOD = 10 ** 9 + 7
INF = 10 ** 10
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000000)
dy = (-1,0,1,0)
dx = (0,1,0,-1)

def main():
    n = int(input())
    s = input()
    rR = [0] * (n + 1)
    rG = [0] * (n + 1)
    rB = [0] * (n + 1)
    
    for i in range(n - 1,-1,-1):
        if s[i] == 'R':
            rR[i] = rR[i + 1] + 1
            rG[i] = rG[i + 1]
            rB[i] = rB[i + 1]
        elif s[i] == 'B':
            rR[i] = rR[i + 1] 
            rG[i] = rG[i + 1]
            rB[i] = rB[i + 1] + 1
        else:
            rR[i] = rR[i + 1] 
            rG[i] = rG[i + 1] + 1
            rB[i] = rB[i + 1]
    
    ans = 0
    for i in range(1,n - 1):
        if s[i] == 'R':
            for j in range(i):
                if s[j] == 'B':
                    if 2 * i - j < n and s[2 * i - j] == 'G':
                        ans += rG[i + 1] - 1
                    else:
                        ans += rG[i + 1]
                elif s[j] == 'G':
                    if 2 * i - j < n and s[2 * i - j] == 'B':
                        ans += rB[i + 1] - 1
                    else:
                        ans += rB[i + 1] 
        elif s[i] == 'B':
            for j in range(i):
                if s[j] == 'R':
                    if 2 * i - j < n and s[2 * i - j] == 'G':
                        ans += rG[i + 1] - 1
                    else:
                        ans += rG[i + 1]
                elif s[j] == 'G':
                    if 2 * i - j < n and s[2 * i - j] == 'R':
                        ans += rR[i + 1] - 1
                    else:
                        ans += rR[i + 1] 
        
        elif s[i] == 'G':
            for j in range(i):
                if s[j] == 'R':
                    if 2 * i - j < n and s[2 * i - j] == 'B':
                        ans += rB[i + 1] - 1
                    else:
                        ans += rB[i + 1]
                elif s[j] == 'B':
                    if 2 * i - j < n and s[2 * i - j] == 'R':
                        ans += rR[i + 1] - 1
                    else:
                        ans += rR[i + 1] 
                        
    print(ans)

if __name__ =='__main__':
    main()

Solution (Python):
def lower_bound(al, key):
    """
    一般に左側が満たしておらず、右側は満たしている判定基準(境目は一つ)ならlower_boundになる
    (条件を満たすもののうち、最小のインデックスを返す)
    単調にさえなっていれば、左右が逆になっていても検索には使える(ng/okも一緒に逆にする必要がある)
    """
    def isOk(a):
        
        
        return a>key

    ng = -1
    ok = len(al)

    while abs(ok-ng)>1:
        mid = (ok+ng)//2

        if isOk(al[mid]):
            ok = mid
        else:
            ng = mid

    return ok

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

d = {"R":[],"G":[],"B":[]}

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

res = 0
for i in range(n-2):
    for j in range(i+1,n-1):
        if s[i]==s[j]:
            continue
        if s[i]=="R":
            if s[j]=="G":
                k = "B"
            else:
                k = "G"
        elif s[i]=="G":
            if s[j]=="R":
                k = "B"
            else:
                k = "R"
        else:
            if s[j]=="G":
                k = "R"
            else:
                k = "G"
        
        x = lower_bound(d[k],j)
        if x<0 or x>=len(d[k]):
            continue
        ki = j + (j-i)
        res += len(d[k])-x
        if ki<n and s[ki]==k:
            if s[ki]==k:
                res -= 1
print(res)

Solution (Python):
from collections import Counter
N = int(input())
S = input()
c = Counter(S)
ans = c['R']*c['G']*c['B']
for i in range(N):
  for j in range(i+1,N):
    k = j-i+j
    if k>N-1:
      continue
    if S[i]!=S[j] and S[j]!=S[k] and S[i]!= S[k]:
      ans -= 1
print(ans)

Solution (Python):

from sys import stdin
import sys


def nextLine(): return next(stdin)
def nextStrList(): return nextLine().split()
def nextIntList(): return [int(_) for _ in nextStrList()]


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











	






		
	nums=[0,0,0]
	for i,si in enumerate(s):
		if si=="R": nums[0]+=1
		elif si=="G": nums[1]+=1
		elif si=="B": nums[2]+=1

	
	ss=nums[0]*nums[1]*nums[2]
	for skip in range(n):
		length=skip*2+3
		if length>n: break
		for i0 in range(n-length+1):
			i1=i0+skip+1
			i2=i1+skip+1
			if s[i0]!=s[i1] and s[i1]!=s[i2] and s[i2]!=s[i0]:
				ss-=1
	print(ss)
			
	
if __name__=="__main__":
	main()

Solution (Python):
def resolve():
    n = int(input())
    s = input()
    r = s.count("R")
    g = s.count("G")
    b = s.count("B")
    ans = r * g * b
    for diff in range(1, 1 + (n - 1) // 2):
        for first in range(n - diff * 2):
            i = s[first]
            j = s[first + diff]
            k = s[first + diff * 2]
            if i != j and j != k and k != i:
                ans -= 1
    print(ans)


if __name__ == '__main__':
    resolve()

Solution (Python):
N=int(input())
S=input()
M=[0 if s=='R' else 1 if s=='G' else 2 for s in S]

C = [[0] * (N+1) for _ in range(3)]
for i in range(N-1,-1,-1):
    for j in range(3):
        C[j][i] = C[j][i+1]+1 if M[i]==j else C[j][i+1]

ans=0
for i in range(N):
    for j in range(i+1,N):
        if M[i]==M[j]: continue
        k=3-M[i]-M[j]
        ans+=C[k][j+1]
        if j+(j-i) < N and M[j+(j-i)]==k: ans-=1
print(ans)

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

def jdg(i,j):
    mm = j+(j-i)
    
    if mm<N:
        if S[mm]==S[i] or S[mm]==S[j]:
            return True  
        else:
            return False
    else:
        return True

mm1 = S.count("R")
mm2 = S.count("G")
mm3 = S.count("B")

ans = mm1*mm2*mm3

for i in range(N-2):
    for j in range(i+1,N-1):
        if jdg(i,j) or S[i]==S[j]:
            continue
        else:
            ans -= 1

print(ans)

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

a = s.count('R')
b = s.count('G')
c = s.count('B')

ans = a * b * c

m = (n-1) // 2
ans = a * b * c
for d in range(1, n):
    if d * 2 >= n:
        break
    for i in range(n):
        if i + d * 2 >= n:
            break
        if s[i] != s[i+d] and s[i] != s[i+d*2] and s[i+d] != s[i+d*2]:
            ans -= 1

print(ans)

Solution (Python):
n = int(input())
s = list(input().strip().lower())
r = 0
g = 0
b = 0
extra = 0
for i in range(n):
    if s[i] == 'r':
        r += 1
    elif s[i] == 'g':
        g += 1
    elif s[i] == 'b':
        b += 1

    for j in range(1, min(i + 1, n - i)):
        left = s[i - j]
        mid = s[i]
        right = s[i + j]
        if left != mid and left != right and mid != right:
            extra += 1

print(r*g*b-extra)

Solution (Python):
N = int(input())
S = input()
r = 0
g = 0
b = 0
ans = 0

for i in range(N):
    if S[i] == 'R':
        r += 1
        ans += g * b
        for j in range(i-1,-1,-1):
            if 2*j-i >= 0 and set([S[j],S[2*j-i]]) == set(['G','B']):
                ans -= 1
    elif S[i] == 'G':
        g += 1
        ans += b * r
        for j in range(i-1,-1,-1):
            if 2*j-i >= 0 and set([S[j],S[2*j-i]]) == set(['B','R']):
                ans -= 1
    else:
        b += 1
        ans += r * g
        for j in range(i-1,-1,-1):
            if 2*j-i >= 0 and set([S[j],S[2*j-i]]) == set(['R','G']):
                ans -= 1

print(ans)

Solution (Python):
n = int(input())
s = input()
color = {"R":0, "G":0, "B":0}
for i in range(n):
    color[s[i]] += 1
temp = color["R"] * color["G"] * color["B"]
count = 0
for i in range((n - 1) // 2):
    for j in range(n - (i + 1) * 2):
        if s[j] != s[j + i + 1] and s[j] != s[j + i * 2 + 2] and s[j + i + 1] != s[j + i * 2 + 2]:
            count += 1
print(temp - count)