Problem:


Score : 400 points

Problem Statement

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

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

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

j - i \neq k - j.

Constraints

1 \leq N \leq 4000

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

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of triplets in question.

Sample Input 1

4
RRGB

Sample Output 1

1

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

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800



Sample input:
4
RRGB


Sample output:
1

Submission status: Accepted

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

count = S.count('R')*S.count('G')*S.count('B')

for i in range (0, N-2):
  colour1 = S[i]
  for j in range (i+1, N-1):
    colour2 = S[j]
    if colour1 == colour2:
      continue
    else:
      if 2*j-i > N-1:
        continue
      elif colour1 != S[2*j-i] and colour2 != S[2*j-i]:
          count-=1
      else:
          continue

print(count)

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())
rli = []
gli = []
bli = []
for i in range(N):
    if S[i] == "R":
        rli.append(i+1)
    if S[i] == "G":
        gli.append(i+1)
    if S[i] == "B":
        bli.append(i+1)
ans = len(rli)*len(gli)*len(bli)
for i in range(N):
    for j in range(i+1, ((N-i)//2+(N-i)%2)+i):
        if S[i] != S[j] and S[j] != S[2*j-i] and S[2*j-i] != S[i]:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
import itertools

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

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

RGBs = list(itertools.permutations(['R', 'G', 'B'], 3))
for i, s in enumerate(S):
  if s == 'R': R.append(i)
  if s == 'G': G.append(i)
  if s == 'B': B.append(i)
out = len(R) * len(G) * len(B)
for i in range(1, N):
  for j in range(N-i*2):
    if (S[j], S[j+i], S[j+i*2]) in RGBs:
      out -= 1
print(out)

Submission status: Accepted

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

smap = {
    'R': 0,
    'G': 1,
    'B': 2,
}

def get_t(a, b):
    a, b = smap[a], smap[b]
    if a + b == 1:
        return 2
    elif a + b == 3:
        return 0
    else:
        return 1

d = [[0 for _ in range(3)] for _ in range(N)]

for i in range(N):
    for j in range(N):
        if i < j:
            s = S[j]
            d[i][smap[s]] += 1

ans = 0
for j in range(1, N-1):
    c = S[j]
    for i in range(0, j):        
        l = S[i]
        if c == l:
            continue
        t = get_t(c, l)
            
        if j + j - i < N and smap[S[j + (j - i)]] == t:
            ans -= 1
        ans += d[j][t]

print(ans)

Submission status: Accepted

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

ans=0
a=0
b=0
c=0
for i in range(n):
    if s[i]=="R":
        a+=1
    if s[i]=="G":
        b+=1
    if s[i]=="B":
        c+=1
ans=a*b*c

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

print(ans)

Submission status: Accepted

Solution code:
import math
n = int(input())
s = input()
r_cnt = 0
g_cnt = 0
b_cnt = 0
for i in s:
    if i == 'R':
        r_cnt += 1
    elif i == 'G':
        g_cnt += 1
    elif i == 'B':
        b_cnt += 1
        
total = r_cnt*g_cnt*b_cnt

if n < 4:
    print(0)

else:
    for i in range(1,math.floor((len(s)-2)/2)+10):
        for j in range(n-2*i):
            tmp = s[j]+s[j+i]+s[j+2*i]
            if (tmp == 'RGB') or (tmp == 'RBG') or (tmp == 'GBR') or (tmp == 'GRB') or (tmp == 'BRG') or (tmp == 'BGR'):
                total -= 1

    print(total)

Submission status: Accepted

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

rc = s.count('R')
gc = s.count('G')
bc = s.count('B')

ans = rc*gc*bc

for i in range(n):
    if s[i] == 'R':
        for j in range(1,min(n-i-1, i)+1):
            if s[i-j] != s[i+j] and s[i-j] != 'R' and s[i+j] != 'R':
                ans -= 1
        for j in range(1,int((n-i-1)/2)+1):
            if s[i+2*j] != s[i+j] and s[i+2*j] != 'R' and s[i+j] != 'R':
                ans -= 1
        for j in range(1,int(i/2)+1):
            if s[i-j] != s[i-2*j] and s[i-j] != 'R' and s[i-2*j] != 'R':
                ans -= 1

print(ans)

Submission status: Accepted

Solution code:
import collections
import math

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

if 'R' in S and 'G'in S and 'B' in S:
    count = collections.Counter(S)
    c_value = list(count.values())
    con = c_value[0]*c_value[1]*c_value[2]
else:
    con = 0

for i in range(N):
    for j in range(i+1, int(math.ceil((N+i)/2))):
        if S[i] != S[j]:
            if S[i] != S[j + (j - i)] and S[j] != S[j + (j - i)]:
                con -= 1

print(con)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
r=0
g=0
b=0
gh=0
for i in range(n):
    if s[i]=='R':
        r=r+1
    elif s[i]=='G':
        g=g+1
    else:
        b=b+1
for j in range(n-2):
    
    for h in range((n-j-1)//2):
        
        if s[j]!=s[j+h+1] and s[j+h+1]!=s[j+2*(h+1)] and s[j]!=s[j+2*(h+1)]:
            gh=gh+1
        else:
            continue
print(r*g*b-gh)

Submission status: Accepted

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

# N = 39
# S = 'RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB'

n_R = S.count('R')
n_G = S.count('G')
n_B = S.count('B')
ans = n_R * n_G * n_B

for b in range(1, N // 2 + 1):
    # b = 2
    for a in range(N - 2 * b):
        # a = 1
        i = a
        j = a + b
        k = a + 2 * b

        if k > N - 1:
            continue

        if S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))

N = INT()
S = input()

ans = 0

count_S = {
    "R": [0] * N,
    "G": [0] * N,
    "B": [0] * N,
}

count_S[S[-1]][-1] = 1
for i in reversed(range(N-1)):
    count_S["R"][i] = count_S["R"][i+1]
    count_S["B"][i] = count_S["B"][i+1]
    count_S["G"][i] = count_S["G"][i+1]
    count_S[S[i]][i] += 1


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


for i in range(0, N-3):
    for j in range(i+1, N-1):
        if S[i] == S[j]:
            continue
        for c in "RGB":
            if S[i] != c and S[j] != c:
                last_color = c
        ans += count_S[last_color][j+1]
        if j+j-i <= N-1 and S[j+j-i] == last_color:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import numpy as np


def solve(*args: str) -> str:
    n = int(args[0])
    S = np.array([0 if c == 'R' else (1 if c == 'G' else 2) for c in args[1]])

    RGB = [np.where(S == 0)[0],
           np.where(S == 1)[0],
           np.where(S == 2)[0]]
    X = [0]*3

    ret = 0
    X[S[0]] += 1
    for j in range(1, n-1):
        X[S[j]] += 1
        a, b = (S[j]+1) % 3, (S[j]-1) % 3
        ret += X[a]*(len(RGB[b])-X[b])
        ret += X[b]*(len(RGB[a])-X[a])
        ret -= len(RGB[a])+len(RGB[b])-len(
            np.unique(np.concatenate([RGB[a]-j, j-RGB[b]]))
        )

    return str(ret)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Accepted

Solution code:
from math import gcd
from functools import reduce
 
n=int(input())
s=input()
 
ret=0
 
for i,x in enumerate(s):
	for j,y in enumerate(s[i+1:],start=i+1):
		if x==y:
			continue
		if i+(j-i)*2 < n :
			z=s[i+(j-i)*2]
			if y!=z!=x:
				ret-=1
 
dic={}
for x in s:
	if not x in dic: 
		dic[x]=0
	dic[x]+=1
 
for i,x in dic.items():
	for j,y in dic.items():
		for k,z in dic.items():
			if i<j<k:
				ret+=x*y*z
print(ret)

Submission status: Accepted

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

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

for i in range(n -2):
    num = 1
    while i + (num)* 2 <= n -1:
        if s[i] != s[i + num] and s[i] != s[i + 2 * num] and s[i + num] != s[i + 2 * num]:
            cnt += 1
        num += 1
print(s.count("R") * s.count("G") * s.count("B") - cnt)

Submission status: Accepted

Solution code:
from itertools import product as pro

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

r = [i for i in range(n) if s[i] == 'R']
g = [i for i in range(n) if s[i] == 'G']
b = [i for i in range(n) if s[i] == 'B']
cnt = len(r) * len(g) * len(b)

length = max(len(r), len(g), len(b))
for i, j, k in [(r, g, b), (g, b, r), (b, r, g)]:
    if length == len(i):
        max1 = set(i)
        min1 = j
        min2 = k

for i, j in pro(min1, min2):
    if 2*j-i in max1:
        cnt -= 1
    if 2*i-j in max1:
        cnt -= 1
    if (i+j)/2 in max1:
        cnt -= 1

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
s = str(input())
rr,gg = [],[]
for i in range(0,len(s)):
    if s[i] == "R":
        rr.append(i)
    elif s[i] == "G":
        gg.append(i)

bb = len(s) -len(rr) -len(gg)
ans = len(rr) * len(gg) * bb
for i in range(0,len(rr)):
    for j in range(0,len(gg)):
        che = 0
        a = rr[i] + gg[j]
        if a % 2 == 0:
            if s[a//2] == "B":
                che += -1
        b = min(rr[i],gg[j]) - abs(rr[i]-gg[j])
        if b >= 0:
            if s[b] == "B":
                che += -1
        c = a - b
        if c < n:
            if s[c] == "B":
                che += -1
        ans += che

print(ans)

Submission status: Accepted

Solution code:
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(1, N-1):
    now = S[i]
    for j in range(1, min(i, N-1-i)+1):
        if len(set([S[i-j], now, S[i+j]])) == 3:
            ans -= 1


print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
N = int(input())
S = input()

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

d = defaultdict(int)
for i in range(N):
    if S[i] == 'R':
        R.append(i+1)
    elif S[i] == 'G':
        G.append(i+1)
    else:
        B.append(i+1)
        d[i+1] = 1

res = 0
bl = len(B)
sb = set(B)
for r in R:
    for g in G:
        for b in [2*r-g, 2*g-r, g+(r-g)/2]:
            res -= d[b]
        res += bl


#        for k in B:
#            res += 1

print(res)

Submission status: Accepted

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

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

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

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

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

Slen = len(S)
hikukazu = 0
for i in range(Slen):
    for num in range(1,Slen//2+1):
        j = i+num
        k = i+num*2
        if k>Slen-1:
            break
        if S[i]!=S[j] and S[i]!=S[k] and S[k]!=S[j]:
            hikukazu += 1

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

Submission status: Accepted

Solution code:
from collections import deque, Counter
from itertools import chain, combinations
import json
# import numpy as np
import bisect
import sys
import math
import bisect

sys.setrecursionlimit(10 ** 8)
# mem = {}

M = 10 ** 9 + 7


def f(rs, gs, bs):
    res = 0
    lgs = len(gs)
    lbs = len(bs)
    for i in rs:
        j = bisect.bisect_left(gs, i)
        k = bisect.bisect_left(bs, i)
        res += (lgs - j) * (lbs - k)

        for jj in range(j, lgs):
            d = (gs[jj] - i)
            index = bisect.bisect_left(bs, i + 2 * d)
            if index != lbs:
                if bs[index] == i + 2 * d:
                    res -= 1

        for kk in range(k, lbs):
            d = (bs[kk] - i)
            index = bisect.bisect_left(gs, i + 2 * d)
            if index != lgs:
                if gs[index] == i + 2 * d:
                    res -= 1


        # for j in reversed(gs):
        #     if not (i < j):
        #         break
        #     for k in reversed(bs):
        #         if not (i < k):
        #             break
        #         if j < k:
        #             if (j - i) != k - j:
        #                 res += 1
        #         else:
        #             if (k - i) != j - k:
        #                 res += 1

    return res


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

    rs = []
    gs = []
    bs = []

    for i, c in enumerate(S):
        if c == 'R':
            rs.append(i)
        elif c == 'G':
            gs.append(i)
        else:
            bs.append(i)
    print(f(rs, gs, bs) + f(gs, rs, bs) + f(bs, rs, gs))


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

print(sum - minus)

Submission status: Accepted

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

if len(S) <= 3:
    print(0)
    exit()

sorted_S = sorted(S)
c = [0, 0, 0]
j = 0
for i in range(len(sorted_S) - 1):
    if sorted_S[i] != sorted_S[i + 1]:
        if j == 0:
            c[j] = i + 1
            j += 1
        else:
            c[j] = (i + 1) - c[j - 1]
            j += 1

# print('c', c, j)
if j != 2:
    print(0)
    exit()
c[2] = N - c[0] - c[1]

condition1 = c[0] * c[1] * c[2]
# print('condition1', condition1)

condition2 = 0
for i in range(N):
    for d in range(N // 2 + 2):
        j = i + d
        k = j + d
        if j >= N or k >= N:
            continue
        # print('i, j, k', i, j, k)
        if (S[i] != S[j]) and (S[j] != S[k]) and (S[k] != S[i]):
            condition2 += 1
ans = condition1 - condition2
print(ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc162/tasks/abc162_d

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


def colors(target, a, b):
    for i in range(N):
        for j in range(i + 1, N):
            if S[i] == a and S[j] == b:
                target[i] += 1


rg = [0 for _ in range(N)]
colors(rg, 'R', 'G')
gr = [0 for _ in range(N)]
colors(gr, 'G', 'R')

gb = [0 for _ in range(N)]
colors(gb, 'G', 'B')
bg = [0 for _ in range(N)]
colors(bg, 'B', 'G')

rb = [0 for _ in range(N)]
colors(rb, 'R', 'B')
br = [0 for _ in range(N)]
colors(br, 'B', 'R')

ans = 0
for i in range(N):
    if S[i] == 'B':
        for j in range(i + 1, N):
            ans += rg[j]
            ans += gr[j]

            k = j + j - i
            if k >= N:
                continue
            if S[i] == 'B' and S[j] == 'R' and S[k] == 'G':
                ans -= 1
            if S[i] == 'B' and S[j] == 'G' and S[k] == 'R':
                ans -= 1

    if S[i] == 'R':
        for j in range(i + 1, N):
            ans += gb[j]
            ans += bg[j]

            k = j + j - i
            if k >= N:
                continue
            if S[i] == 'R' and S[j] == 'G' and S[k] == 'B':
                ans -= 1
            if S[i] == 'R' and S[j] == 'B' and S[k] == 'G':
                ans -= 1

    if S[i] == 'G':
        for j in range(i + 1, N):
            ans += rb[j]
            ans += br[j]

            k = j + j - i
            if k >= N:
                continue
            if S[i] == 'G' and S[j] == 'R' and S[k] == 'B':
                ans -= 1
            if S[i] == 'G' and S[j] == 'B' and S[k] == 'R':
                ans -= 1

print(ans)

Submission status: Accepted

Solution code:
import math
import copy
import sys
import fractions
# import numpy as np
# import statistics
import decimal
import heapq
import collections
import itertools
import bisect

# from operator import mul

sys.setrecursionlimit(100001)


# input = sys.stdin.readline
# sys.setrecursionlimit(10**6)

# ===FUNCTION===

def getInputIntList():
    outputDataList = []
    inputData = input().split()
    outputDataList = [int(n) for n in inputData]

    return outputDataList


def getSomeInputInt(n):
    outputDataList = []
    for i in range(n):
        inputData = int(input())
        outputDataList.append(inputData)

    return outputDataList


def getSomeInputListInt(n):
    inputDataList = []
    outputDataList = []
    for i in range(n):
        inputData = input().split()
        inputDataList = [int(n) for n in inputData]
        outputDataList.append(inputDataList)

    return outputDataList


# ===CODE===

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

ruisekiwa = []
tmp = [0 for _ in range(3)]

for si in s:
    if si == "R":
        tmp[0] += 1
    elif si == "G":
        tmp[1] += 1
    else:
        tmp[2] += 1
    tmpra = copy.deepcopy(tmp)
    ruisekiwa.append(tmpra)

ans = 0
for j in range(1, n - 1):
    sj = 0
    if s[j] == "R":
        sj = 0
    elif s[j] == "G":
        sj = 1
    else:
        sj = 2

    tmpa = ruisekiwa[j - 1]
    tmpb = [0 for _ in range(3)]
    for tmp in range(3):
        tmpb[tmp]=ruisekiwa[n - 1][tmp] - ruisekiwa[j][tmp]

    for a in range(3):
        for b in range(3):
            if a == b:
                continue
            if a == sj or b == sj:
                continue
            ans += tmpa[a] * tmpb[b]

    hikukazu = 0
    for e in range(1, 4000):
        if not(-1< j-e < j+e < n):
            break
        if s[j-e] != s[j] and s[j] != s[j+e] and s[j-e] != s[j+e]:
            hikukazu += 1

    ans -= hikukazu

print(ans)

Submission status: Accepted

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

R_count = S.count("R")
B_count = S.count("B")
G_count = S.count("G")

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

print((R_count*B_count*G_count) - t)

Submission status: Accepted

Solution code:
N = int(input())
S = list(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

sumR = sum(R)
sumG = sum(G)
sumB = sum(B)

cnt = 0
for i in range(N):
    sumR -= R[i]
    sumG -= G[i]
    sumB -= B[i]
    sum_r = sumR
    sum_g = sumG
    sum_b = sumB
    for j in range(i + 1, N):
        sum_r -= R[j]
        sum_g -= G[j]
        sum_b -= B[j]
        check_index = j + (j - i)
        if S[j] == 'R':
            if S[i] == 'B':
                cnt += sum_g
                if check_index < N:
                    cnt -= G[check_index]
            if S[i] == 'G':
                cnt += sum_b
                if check_index < N:
                    cnt -= B[check_index]
        elif S[j] == 'G':
            if S[i] == 'R':
                cnt += sum_b
                if check_index < N:
                    cnt -= B[check_index]
            if S[i] == 'B':
                cnt += sum_r
                if check_index < N:
                    cnt -= R[check_index]
        else:
            if S[i] == 'R':
                cnt += sum_g
                if check_index < N:
                    cnt -= G[check_index]
            if S[i] == 'G':
                cnt += sum_r
                if check_index < N:
                    cnt -= R[check_index]
print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
r=[0]*n
b=[0]*n
g=[0]*n
cb=0
cg=0
cr=0
for i in range(n-1,-1,-1):
  if s[i]=='R':
    cr+=1
  elif s[i]=='G':
    cg+=1
  else:
    cb+=1
  r[i]=cr
  g[i]=cg
  b[i]=cb
  
fr=[0]*n
fb=[0]*n
fg=[0]*n
cb=0
cg=0
cr=0
for i in range(n):
  if s[i]=='R':
    cr+=1
  elif s[i]=='G':
    cg+=1
  else:
    cb+=1
  fr[i]=cr
  fg[i]=cg
  fb[i]=cb
  
p=0
for i in range(1,n-1):
  if s[i]=='B':
    p+=fg[i-1]*r[i+1]+fr[i-1]*g[i+1]
    j=i-1
    k=i+1
    while (j>-1 and k<n):
      if (s[j]=='G' and s[k]=='R' or s[j]=='R' and s[k]=='G'):
        p-=1
      j-=1
      k+=1
      
  if s[i]=='G':
    p+=fb[i-1]*r[i+1]+fr[i-1]*b[i+1]
    j=i-1
    k=i+1
    while (j>-1 and k<n):
      if (s[j]=='B' and s[k]=='R' or s[j]=='R' and s[k]=='B'):
        p-=1
      j-=1
      k+=1
      
  if s[i]=='R':
    p+=fb[i-1]*g[i+1]+fg[i-1]*b[i+1]
    j=i-1
    k=i+1
    while (j>-1 and k<n):
      if (s[j]=='B' and s[k]=='G' or s[j]=='G' and s[k]=='B'):
        p-=1
      j-=1
      k+=1
  
print(p)

Submission status: Accepted

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

r = []
g = []
b = []
for i in range(n):
    if s[i]=="R":
        r.append(i)
    elif s[i]=="G":
        g.append(i)
    elif s[i]=="B":
        b.append(i)
    else:
        pass
# print(r,g,b)
count = 0
for i in range(n):
    x = s[i]
    for sa in range(n):
        j = i + sa
        k = j + sa
        if j<n:
            y = s[j]
        else:
            break
        if k<n:
            z = s[k]
        else:
            break
        if x!=y and y!=z and z!=x:
            count += 1
# print(count)
ans = len(r) * len(g) * len(b) - count
print(ans)

Submission status: Accepted

Solution code:
def main():
    n=int(input())
    s=input()
    r,g,b=[],[],[]
    if n<=3:
        print(0)
    else:
        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(len(r)):
            for j in range(len(g)):
                if (r[i]+g[j])%2==0 and s[(r[i]+g[j])//2]=="B":
                        ans-=1
        for i in range(len(g)):
            for j in range(len(b)):
                if (g[i]+b[j])%2==0 and s[(g[i]+b[j])//2]=="R":
                        ans-=1
        for i in range(len(r)):
            for j in range(len(b)):
                if (r[i]+b[j])%2==0 and s[(r[i]+b[j])//2]=="G":
                        ans-=1
        print(ans)
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
s = input()
r = []
g = []
b = []
for i in range(n):
    if s[i] == "R":
        r.append(i)
    elif s[i] == "G":
        g.append(i)
    else:
        b.append(i)
ans = len(r)*len(g)*len(b)
for i in b:
    for j in g:
        a = max(i,j)
        u = min(i,j)
        if a*2-u >= 0 and a*2-u < n :
            if s[a*2-u] == 'R':
                ans -= 1
        if 2*u-a >= 0 and 2*u-a < n:
            if s[2*u-a] == 'R':
                ans -= 1
        if (a-u)%2 == 0 and u+(a-u)/2 >= 0 and u+(a-u)/2 < n:
            if s[u+(a-u)//2] == 'R':
                ans -= 1
print(ans)

Submission status: Accepted

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

r = list()
g = list()
b = list()
for idx, si in enumerate(s):
    if si == 'R':
        r.append(idx)
    elif si == 'G':
        g.append(idx)
    else:
        b.append(idx)

ret = 0
bi_cnt = len(b)
for ri in r:
    for gi in g:
        cnt = 0
        try:
            dan1 = 2*ri - gi
            if (dan1 > 0) & (s[dan1] == 'B'):
                cnt += 1
        except:
            pass

        try:
            dan3 = 2*gi - ri
            if (dan3 > 0) & (s[dan3] == 'B'):
                cnt += 1
        except:
            pass

        try:
            dan2, mod = divmod(ri+gi, 2)
            if (mod == 0) & (s[dan2] == 'B'):
                cnt += 1
        except:
            pass

        ret += (bi_cnt - cnt)

print(ret)

Submission status: Accepted

Solution code:
from collections import Counter


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

# 等間隔に並んでいる
count = 0

for start in range(N):
  offset = 1
  while True: 
      middle = start + offset
      end = middle + offset

      if end >= N:
          break

      s = {S[start], S[middle], S[end]}

      if len(s) == 3:
          count += 1

      offset += 1

c = Counter(S)

if len(c) != 3:
  print(0)
else:  
  x, y, z = c.values()
  print(x * y * z - count)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
a=n*(n-1)*(n-2)//6
r=s.count("R")
g=s.count("G")
b=s.count("B")
ra=r*(r-1)*(r-2)//6+(r*(r-1)//2)*(n-r)
ga=g*(g-1)*(g-2)//6+(g*(g-1)//2)*(n-g)
ba=b*(b-1)*(b-2)//6+(b*(b-1)//2)*(n-b)
sum=0
for i in range((n-3)//2+1):
	#print(i)
	for j in range(n-(2*i+3)+1):
		#print(s[j],s[j+i+1],s[j+2*(i+1)] )
		if not (s[j]==s[j+i+1] or s[j]==s[j+2*(i+1)] or s[j+i+1]==s[j+2*(i+1)] ):
			sum+=1
#print(r,g,b,ra,ga,ba,sum,a)
print(a-(ra+ga+ba)-sum)

Submission status: Accepted

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

def rest(a):
    if a == "R":
        return(["G", "B"])
    elif a == "G":
        return(["R", "B"])
    else:
        return (["R", "G"])

for i in range(n - 3):
    rest1 = rest(s[i])[0]
    rest2 = rest(s[i])[1]
    ans = ans + s[i + 1:].count(rest1) * s[i + 1:].count(rest2)

    j = i + 1
    k = 1
    while True:
        if (s[j] == rest1 and s[j + k] == rest2) or (s[j] == rest2 and s[j + k] == rest1):
            ans = ans - 1
        k = k + 1
        j = i + k
        if j + k > n - 1:
            break

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
dp = [[0] * 7 for i in range(4001)]

for i in range(n):
    if s[i] == 'R':
        dp[i + 1][0] = dp[i][0] + 1
        dp[i + 1][1] = dp[i][1]
        dp[i + 1][2] = dp[i][2]
        dp[i + 1][3] = dp[i][1] + dp[i][3]
        dp[i + 1][4] = dp[i][4]
        dp[i + 1][5] = dp[i][2] + dp[i][5]
        dp[i + 1][6] = dp[i][6] + dp[i][4]
    elif s[i] == 'G':
        dp[i + 1][0] = dp[i][0]
        dp[i + 1][1] = dp[i][1] + 1
        dp[i + 1][2] = dp[i][2]
        dp[i + 1][3] = dp[i][0] + dp[i][3]
        dp[i + 1][4] = dp[i][2] + dp[i][4]
        dp[i + 1][5] = dp[i][5]
        dp[i + 1][6] = dp[i][6] + dp[i][5]
    else:
        dp[i + 1][0] = dp[i][0]
        dp[i + 1][1] = dp[i][1]
        dp[i + 1][2] = dp[i][2] + 1
        dp[i + 1][3] = dp[i][3]
        dp[i + 1][4] = dp[i][1] + dp[i][4]
        dp[i + 1][5] = dp[i][0] + dp[i][5]
        dp[i + 1][6] = dp[i][6] + dp[i][3]
    for j in range(1, i // 2 + 1):
        if s[i] != s[i - j] and s[i] != s[i - j * 2] and s[i - j] != s[i - 2 * j]:
            dp[i + 1][6] -= 1
print(dp[n][6])

Submission status: Accepted

Solution code:
# 整数を一つ入力
N = int(input())

# 文字列を一つ入力
S = input()

res = 0

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

for i in range(N):
    if S[i] == "R":
        R.append(i)
        continue
    if S[i] == "G":
        G.append(i)
        continue
    B.append(i)

BN = len(B)

for i in R:
    for j in G:
        res += BN
        ii,jj = i,j
        if ii > jj:
            ii,jj = jj,ii
        if ii - (jj-ii) >= 0:
            if S[ii-(jj-ii)] == "B":
                res -= 1
        if (abs(jj-ii)) % 2 == 0:
            if S[(jj+ii) // 2] == "B":
                res -= 1
        if jj + (jj-ii) <= N-1:
            if S[jj+(jj-ii)] == "B":
                res -= 1
print(res)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
afters={'R':0, 'B':0, 'G':0}
for i in range(n):
    afters[s[i]] += 1

befores = {'R':0, 'B':0, 'G':0}
befores[s[0]]+=1
afters[s[0]]-=1

ans=0
for i in range(1,n-1):
    head=s[0:i]
    last=s[i+1::]
    afters[s[i]]-=1
    if s[i]=='R':
        ans += befores['G'] * afters['B'] + befores['B'] * afters['G'] 
        bad =[['G','B'],['B','G']]
    elif s[i]=='B':
        ans += befores['G'] * afters['R'] + befores['R'] * afters['G'] 
        bad = [['G','R'],['R','G']]
    else:
        ans += befores['B'] * afters['R'] + befores['R'] * afters['B'] 
        bad = [['B','R'],['R','B']]
    for j in range(min(i-0, n-i-1)):
        if [s[i-j-1], s[i+j+1]] in bad:
            ans -= 1
    befores[s[i]]+=1
    

print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations
N = int(input())
S = input()
ans = 0
memo = {
    "R": [0] * (N+1),
    "G": [0] * (N+1),
    "B": [0] * (N+1),
}
for i in range (N-1, -1, -1):
    memo["R"][i] = memo["R"][i+1] + int(S[i] == "R")
    memo["G"][i] = memo["G"][i+1] + int(S[i] == "G")
    memo["B"][i] = memo["B"][i+1] + int(S[i] == "B")
for a, b, c in permutations(['R', 'G', 'B']):
    i = -1
    while i < N-3:
        i += 1
        if S[i] != a: continue
        j = i
        while j < N-2:
            j += 1
            if S[j] != b: continue
            ans += memo[c][j]
            if j + (j-i) < N: ans -= int(S[j+(j-i)] == c)
print(ans)

Submission status: Accepted

Solution code:
from time import time

def solve(N, S):
    answer = 0
    Cs = [[], [], []]
    for i in range(N):
        c = S[i]
        if c == 'R':
            Cs[0].append(i)
        elif c == 'G':
            Cs[1].append(i)
        elif c == 'B':
            Cs[2].append(i)
    answer = len(Cs[0]) * len(Cs[1]) * len(Cs[2])
    for i in range(N):
        for d in range(1, N-i):
            if i + 2*d < N and not(S[i] == S[i+d] or S[i] == S[i+2*d] or S[i+d*2] == S[i+d]):
                answer -= 1
    print(answer)


def main(N, S):
    import sys
    start = time()
    from itertools import combinations
    Cs = [[], [], []]
    for i in range(N):
        c = S[i]
        if c == 'R':
            Cs[0].append(i)
        elif c == 'G':
            Cs[1].append(i)
        elif c == 'B':
            Cs[2].append(i)
    answer = 0
    for C in Cs:
        a = 0
        print(C, len(C))
        for Ci in range(len(C)-1):
            i = C[Ci]
            for Cj in range(Ci+1, len(C)):
                j = C[Cj]
                print("*", i, j)
                print(i)           # i より前
                print(j - i - 1)   # i と j の間
                print(N - 1 - j)   # j より後
                print(Ci)
                print(Cj - Ci-1)
                print(len(C) - 1 - Cj)
                a += i           # i より前
                a += N - 1 - j   # j より後
                a += j - i - 1   # i と j の間
                a -= Ci
                a -= Cj - Ci-1
                a -= len(C) - 1 - Cj
        print(S[C[0]], "expect", sum(S[C[0]] in (i, j, k) and (i == j or j == k or i == k) for i,j,k in combinations(S, 3)))
        print(S[C[0]], "actual", a)
        answer += a
    print("expect", sum(i == j or j == k or i == k for i,j,k in combinations(S, 3)))
    print("actual", answer)

    print(answer, time() - start, file=sys.stderr)
    for i in range(N):
        for d in range(1, N-i):
            if i + 2*d < N and not(S[i] == S[i+d] or S[i] == S[i+2*d]):
                answer += 1
    total = N * (N-1)*(N-2) // 6
    print(total, answer, file=sys.stderr)
    print(total - answer)
    print(time() - start, file=sys.stderr)


N = int(input())
S = input()
solve(N, S)
#main(N, S)

Submission status: Accepted

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

count = 0

r_idx = set([n for n, v in enumerate(s) if v == 'R'])
g_idx = set([n for n, v in enumerate(s) if v == 'G'])
b_idx = set([n for n, v in enumerate(s) if v == 'B'])


# ループ2重に減らして，3個目をinで探索
for r in r_idx:
	for g in g_idx:
		out = 0
		if max([r,g]) + abs(g-r) in b_idx:
			out += 1
		if min([r,g]) - abs(g-r) in b_idx:
			out += 1
		if (r+g) / 2 in b_idx:
			out += 1
		count += (len(b_idx) - out)



print(count)