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:
#!/usr/bin/env python3
import sys


def solve(N: int, S: str):
    R = [0] * N
    G = [0] * N
    B = [0] * N
    for i, s in enumerate(S):
        if s == 'R':
            if i == 0:
                R[i] += 1
            else:
                R[i] += R[i-1] + 1
        else:
            if i == 0:
                R[i] == 0
            else:
                R[i] += R[i-1]
        if s == 'G':
            if i == 0:
                G[i] += 1
            else:
                G[i] += G[i-1] + 1
        else:
            if i == 0:
                G[i] == 0
            else:
                G[i] += G[i-1]
        if s == 'B':
            if i == 0:
                B[i] += 1
            else:
                B[i] += B[i-1] + 1
        else:
            if i == 0:
                B[i] == 0
            else:
                B[i] += B[i-1]
    counter = 0
    d = {'R': R, 'G': G, "B": B}
    for i in range(N):
        for j in range(N-1, i+1, -1):
            if S[i] == S[j]:
                continue
            l = ['R', 'G', 'B']
            l.remove(S[i])
            l.remove(S[j])
            L = d[l[0]]
            counter += L[j] - L[i]
            if (j-i) % 2 == 0 and S[(j+i)//2] == l[0]:
                counter -= 1
    print(counter)
    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    S = next(tokens)  # type: str
    solve(N, S)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
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
ans = R * G * B
for i in range(1, N//2+1):
    for j in range(0, N - (i*2)):
        k = j + i
        l = k + i
        if S[j] != S[k] and S[k] != S[l] and S[l] != S[j]:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
rgb = ['R','G','B']

ans = 0
for j in range(1,n-1):
    rgb_tmp = [i for i in rgb if i!=s[j]]
    for a in range(2):
        color_i, color_k = rgb_tmp[a], rgb_tmp[a-1]
        ans += s[:j].count(color_i) * s[j+1:].count(color_k)
        
        for b in range(min(j,n-j-1)+1):
            if s[j-b] == color_i and s[j+b] == color_k:
                ans-=1
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

def calc(s):
    positions = {'R': [], 'G': [], 'B': []}
    positions_s = {'R': set(), 'G': set(), 'B': set()}
    for i, ch in enumerate(s):
        positions[ch].append(i)
        positions_s[ch].add(i)
    ans = 0

    for i in range(len(s)):
        for j in range(i + 1, len(s)):
            if s[i] != s[j]:
                for c3 in 'RGB':
                    if c3 not in (s[i], s[j]):
                        break
                k0 = bisect_left(positions[c3], j + 1)
                ans += len(positions[c3]) - k0
                if j + j - i in positions_s[c3]:
                    ans -= 1
    return ans


print(calc(s))

Submission status: Accepted

Solution code:
from collections import defaultdict
N = int(input())
S = input()
rgb_list = [[] for i in range(3)]
rgb2index = {'R':0, 'G':1, 'B':2}
for i, s in enumerate(S):
    rgb_list[rgb2index[s]] += [i]
rgb_list = sorted(rgb_list, key=len)
other_index = set(rgb_list[2])
ans = 0
len_other = len(other_index)
count = 1
for i in rgb_list[0]:
    for j in rgb_list[1]:
        diff = abs(i-j)
        tmp = - int((min(i, j) - diff) in other_index) - int((max(i, j) + diff) in other_index)
        if diff % 2 == 0 and (max(i, j) - diff//2) in other_index:
            tmp -= 1
        ans += len_other + tmp
print(ans)

Submission status: Accepted

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

lr = [0]*n
lb = [0]*n

ans = 0
r = 0
g = 0
b = 0
for i in range(n):
    if s[i]=="R":
        r += 1 
    elif s[i]=="G":
        g += 1
    else:
        b += 1
ans = r*b*g


for i in range(n):
    ans += lr[i]*lb[i]

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

Submission status: Accepted

Solution code:
N = int(input())
S = input()
R_lst = []
G_lst = []
B_lst = []
B_exist = [0] * N
for i in range(N):
    if S[i] == 'R':
        R_lst.append(i)
    elif S[i] == 'G':
        G_lst.append(i)
    else: #S[i] == 'B'
        B_lst.append(i)
        B_exist[i] = 1

ans = 0
B_len = len(B_lst)
for r in R_lst:
    for g in G_lst:
        if r < g:
            i, j = r, g
        else:
            i, j = g, r
        ans += B_len

        flug = False
        if j + j - i >= N:
            flug = False
        elif B_exist[j + j - i]:
            flug = True
        if flug:
            ans -= 1
        
        flug = False
        if i - (j - i) < 0:
            flug = False
        elif B_exist[i - (j - i)]:
            flug = True
        if flug:
            ans -= 1
            
        flug = False
        if (i + j) / 2 % 1 != 0:
            flug = False
        elif B_exist[(i + j) // 2]:
            flug = True
        if flug:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
D = {"R": [], "G": [], "B": []}
for i in range(N):
  D[S[i]].append(i)
p = 1
for i in D:
  p *= len(D[i])
cnt = 0
for i in range(N):
  for j in range(i+1, N):
    if 2 * j - i < N:
      if S[i] != S[j] and S[j] != S[2*j-i] and S[2*j-i] != S[i]:
        cnt += 1
print(p-cnt)

Submission status: Accepted

Solution code:
# coding: utf-8
import re

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

R = set([m.start() for m in re.finditer('R', s)])
G = set([m.start() for m in re.finditer('G', s)])
B = set([m.start() for m in re.finditer('B', s)])
#print(R,G,B)
x=0
li=[]
for r in R:
    for g in G:
        
        if r < g:
            gr = g-r
            li.extend([r-gr in B, g+gr in B, (gr%2 == 0 and r+gr//2 in B)])
        
        else:
            rg = r-g
            li.extend([g-rg in B, r+rg in B, (rg%2 == 0 and g+rg//2 in B)])

print(len(R)*len(G)*len(B)-sum(li))

Submission status: Accepted

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

rnum=s.count("R")
gnum=s.count("G")
bnum=s.count("B")

#３つがすべて違う組の数

dif=rnum*gnum*bnum

#どれか２つ以上が同じ組の数

two=n*(n-1)*(n-2)//6-dif
# print(dif)
# print(two)
#j-i=k-jの組
straid=0
samax=n//2

for i in range(1,samax+1):
    for j in range(n-2*i):
        a=list(s[j:j+2*i+1:i])
        a.sort()
        if a==["B","G","R"]:
            straid+=1
            
# print(straid)
ans=two+straid
print(n*(n-1)*(n-2)//6-ans)

Submission status: Accepted

Solution code:
N=int(input())
S=input()
SS=[a for a in S]
SS.insert(0,0)
nr=S.count("R")
ng=S.count("G")
nb=S.count("B")
n=0
for i in range(1,N-1):
    for j in range(i+1,N):
        k=j*2-i
        if k<=N :
            if SS[i]!=SS[j] and SS[j]!=SS[k] and SS[k]!=SS[i]:
                n+=1
answer=nr*ng*nb-n
print(answer)

Submission status: Accepted

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

IN=lambda : map(int, input().split())
mod=1000000007

#+++++

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



def other_c(a,b):
	if a in 'RG' and b in 'RG':
		return 'B'
	elif a in 'GB' and b in 'GB':
		return 'R'
	else:
		return 'G'

def main():
	n = int(input())
	s = list(input())
	zn=[0]*n
	cc=[zn[:], zn[:], zn[:]]
	cc[dd[s[-1]]][-1]=1
	for i in range(n-2,-1,-1):
		c=dd[s[i]]
		for ci in range(3):
			cc[ci][i]+=cc[ci][i+1]+(c==ci)
	#print(cc)
	count=0
	for i in range(n-2):
		ci=s[i]
		for j in range(i+1, n-1):
			if s[j]==ci:
				continue
			other = other_c(ci, s[j])
			ol=dd[other]
			add = cc[ol][j+1]
			if j + (j-i) < n and s[j+(j-i)]==other:
				add -= 1
			count+=add
	print(count)
			
			
	
		
		
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

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)

out=len(R)*len(G)*len(B)
for i in range(len(R)):
    for ii in range(len(G)):
        a=1

for i in range(N-2):
    for ii in range(1,(N-i)//2+(N-i)%2):
        if S[i]!=S[i+ii] and S[i+ii]!=S[i+2*ii] and S[i]!=S[i+2*ii]:
            out-=1

print(out)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
## [color][idx]
RGB = [[0 for i in range(N)] for j in "RGB"]
for idx,ch in enumerate(S):
  for color_idx in [0,1,2]:
    RGB[color_idx][idx] = RGB[color_idx][idx-1]
  RGB["RGB".index(ch)][idx] += 1
ans = 0
for i in range(N-2):
  for j in range(i+1,N-1):
    if S[i] != S[j]:
      nokori = {"R","G","B"} - {S[i],S[j]}
      n_ch = [ch for ch in nokori][0]
      n_idx = "RGB".index(n_ch)
      ans += RGB[n_idx][-1]-RGB[n_idx][j]-(1 if (j+(j-i)<N and  S[j + (j-i)] == n_ch) else 0)
print (ans)

Submission status: Accepted

Solution code:
def nCr(n, r):
    import math
    # nCrのr>nは組み合わせが存在しないので0を返す
    # raiseすべきのこともあるかも
    if r > n:
        return 0
    return math.factorial(n) // ((math.factorial(n - r) * math.factorial(r)))

n = int(input())
s = input()
tr, tg, tb = 0,0,0
for i in range(n):
    if s[i] == "R":
        tr  += 1
    if s[i] == "G":
        tg  += 1
    if s[i] == "B":
        tb  += 1

total = tr*tg*tb
# same color
#total -= nCr(tr, 3)
#total -= nCr(tg, 3)
#total -= nCr(tb, 3)
#print(nCr(n, 3), nCr(tr, 3), nCr(tg, 3), nCr(tb, 3))
#print(total)
# cond 2
for i in range(1, n):
    for j in range(1, min(i, n-i-1) + 1):
        a,b,c = s[i-j], s[i], s[i+j]
        if a != b and b != c and a != c:
            total -= 1
print(total)

Submission status: Accepted

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

R = s.count("R")
G = s.count("G")
B = s.count("B")

sum = R*G*B

for i in range(n):
    for j in range(i+1,n):
        if s[j] != s[i]:
            k = j+j-i
            if k < n and s[k] != s[j] and s[k] != s[i]:
                sum-=1

print(sum)

Submission status: Accepted

Solution code:
from collections import Counter
N = int(input())
S = str(input())
S += "x"*4000
all_string = Counter(S)

after_happen = {0: all_string}
for i in range(1, N+1):
    tmp = after_happen[i-1].copy()
    after_happen[i] = tmp
    after_happen[i][S[i-1]] -= 1
ans = 0
rgb = set(["R", "G", "B"])
for i in range(N-2):
    for j in range(i+1, N-1):
        # 最後に引くのを忘れない
        # j+1以降で探す
        if S[i] == S[j]:
            continue
        target = rgb-set([S[i], S[j]])
        target = list(target)[0]
        # print(target)
        ans += after_happen[j][target]
        # 余分に数えている分を引きたい
        if S[j+(j-i)] == target:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=list(input())
r=[]
g=[]
b=[0]*n
for i in range(len(s)):
	if s[i]=="R":
		r.append(i)
	if s[i]=="G":
		g.append(i)
	if s[i]=="B":
		b[i]=1
ans=0
s=sum(b)
for i in r:
	for j in g:
		ans+=s
		if 0<=2*j-i and 2*j-i<n:
			ans-=b[2*j-i]
		if (i+j)%2==0:
			ans-=b[(i+j)//2]
		if 0<=2*i-j and 2*i-j<n:
			ans-=b[2*i-j]
print(ans)

Submission status: Accepted

Solution code:
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

m=0
for i in range(1,(n+1)//2):
    for j in range(n-2*i):
        A=s[j]
        B=s[j+i]
        C=s[j+2*i]
        if A!=B and B!=C and C!=A:
            m+=1

ans=r*g*b
print(ans-m)

Submission status: Accepted

Solution code:
import bisect
N = int(input())
S = input()
R=[]
G=[]
B=[]
ans=0
for i, s in enumerate(S):
    if s == "R":
        R.append(i)
    elif s == "G":
        G.append(i)
    else:
        B.append(i)
blen=len(B)
for ri in range(len(R)):
    for gi in range(len(G)):
        x, y = sorted([R[ri], G[gi]])
        ans+=blen
        bi = bisect.bisect_left(B,2*y-x)
        if bi < blen and B[bi] == 2*y-x:
            ans -= 1
        bi = bisect.bisect_left(B,(x+y)/2)
        if bi < blen and B[bi] == (x+y)/2:
            ans -= 1
        bi = bisect.bisect_left(B, 2 * x - y)
        if bi < blen and B[bi] == 2 * x - y:
            ans -= 1
print(ans)

Submission status: Accepted

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

Rs = {}
Gs = {}
Bs = {}

ans = 0
minus = 0

for i in range(n):
    if s[i] == "R":
        Rs[i] = 1
    elif s[i] == "G":
        Gs[i] = 1
    elif s[i] == "B":
        Bs[i] = 1

for rk in Rs:
    for gk in Gs:
        dist = gk - rk
        if Bs.get(gk + dist) is not None:
            minus += 1
        if Bs.get(rk - dist) is not None:
            minus += 1
        if abs(dist) % 2 == 0:
            if Bs.get(rk + dist//2) is not None:
                minus += 1

ans = len(Rs) * len(Gs) * len(Bs) - minus

print(ans)

Submission status: Accepted

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

ans = 0
#Num1:
A = [0 for i in range(9)] # r_0 g_1 b_2 rg_3 rb_4 gr_5 gb_6 br_7 bg_8
for i in S:
  if i == 'R':
    A[0] += 1 # r
    A[5] += A[1] # gr = g + [r]
    A[7] += A[2] # br = b + [r]
    ans += A[6] + A[8] # gb[r], bg[r]
  elif i == 'G':
    A[1] += 1 # g
    A[3] += A[0] # rg = r + [g]
    A[8] += A[2] # bg = b + [g]
    ans += A[4] + A[7] # rb[g], br[g]
  else: # i == 'B'
    A[2] += 1 # b
    A[4] += A[0] # rb = r + [b]
    A[6] += A[1] # gb = g + [b]
    ans += A[3] + A[5] # rg[b], gr[b]
#  print(A, ans)
    
#Num2:
for i in range(1, (N+1)//2):
  for j in range(0, N - 2 * i):
    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)

Submission status: Accepted

Solution code:
N = int(input())
S = input().strip()
r = 0
ccr = [0]*(N+1)
ccg = [0]*(N+1)
ccb = [0]*(N+1)
for i in range(N-1, -1, -1):
    ccr[i] = ccr[i+1]
    ccg[i] = ccg[i+1]
    ccb[i] = ccb[i+1]
    if S[i] == "R":
        ccr[i] += 1
    elif S[i] == "B":
        ccb[i] += 1
    else:
        ccg[i] += 1

for i in range(N-1):
    a = S[i]
    for j in range(i+1, N-1):
        b = S[j]
        df = 2*j-i
        if (a == "R" and b == "G") or (a == "G" and b == "R"):
            if df < N and S[df] == "B":
                r -= 1
            r += ccb[j+1]
        elif (a == "R" and b == "B") or (a == "B" and b == "R"):
            if df < N and S[df] == "G":
                r -= 1
            r += ccg[j+1]
        elif (a == "B" and b == "G") or (a == "G" and b == "B"):
            if df < N and S[df] == "R":
                r -= 1
            r += ccr[j+1]
print(r)

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())
n = len(S)
pairs = []
for i, c1 in enumerate(S):
    for j, c2 in enumerate(S[i + 1:], start=i + 1):
        if c1 != c2:
            pairs.append((i, j))
prefix = [[0] * 3 for _ in range(len(S) + 1)]
for i, c in enumerate(S, start=1):
    if c == 'R':
        prefix[i][0] += prefix[i - 1][0] + 1
        prefix[i][1] += prefix[i - 1][1]
        prefix[i][2] += prefix[i - 1][2]
    elif c == 'G':
        prefix[i][1] += prefix[i - 1][1] + 1
        prefix[i][0] += prefix[i - 1][0]
        prefix[i][2] += prefix[i - 1][2]
    else:
        prefix[i][2] += prefix[i - 1][2] + 1
        prefix[i][0] += prefix[i - 1][0]
        prefix[i][1] += prefix[i - 1][1]
res = 0
for i, j in pairs:
    if {S[i], S[j]} == {'R', 'G'}:
        res += prefix[-1][2] - prefix[j + 1][2]
        if 2 * j - i < n and S[2 * j - i] == 'B':
            res -= 1
    elif {S[i], S[j]} == {'R', 'B'}:
        res += prefix[-1][1] - prefix[j + 1][1]
        if 2 * j - i < n and S[2 * j - i] == 'G':
            res -= 1
    elif {S[i], S[j]} == {'B', 'G'}:
        res += prefix[-1][0] - prefix[j + 1][0]
        if 2 * j - i < n and S[2 * j - i] == 'R':
            res -= 1
print(res)

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())
r = S.count('R')
g = S.count('G')
b = S.count('B')
p = r*g*b
a = 0
for i in range(N):
    for j in range(min(i,N-i-1)):
        if S[i] != S[i-j-1] and S[i] != S[i+j+1] and S[i-j-1] != S[i+j+1]:
            a += 1
print(p-a)

Submission status: Accepted

Solution code:
from collections import Counter

N = int(input())
S = input()
res = 1

cc = Counter(S)
if len(cc) < 3:
    res = 0
else:
    for i in cc.values():
        res *= i

k = 1
while k <= N/2:
    for i in range(N-2*k):
        if S[i] != S[i+k] and S[i+k] != S[i+2*k] and S[i] != S[i+2*k]:
            res -= 1
    k+=1

print(res)

Submission status: Accepted

Solution code:
import sys
import bisect

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    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)
    setr = set(r)
    setg = set(g)
    setb = set(b)
    ans = len(r) * len(g) * len(b)

    for i in r:
        for j in range(N):
            if i + j in setg and i + j + j in setb:
                ans -= 1
            if i + j in setb and i + j + j in setg:
                ans -= 1
    for i in g:
        for j in range(N):
            if i + j in setr and i + j + j in setb:
                ans -= 1
            if i + j in setb and i + j + j in setr:
                ans -= 1
    for i in b:
        for j in range(N):
            if i + j in setr and i + j + j in setg:
                ans -= 1
            if i + j in setg and i + j + j in setr:
                ans -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

num_r, num_g, num_b = 0, 0, 0
for i in range(n):
    if s[i] == 'R': num_r += 1
    elif s[i] == 'G': num_g += 1
    else: num_b += 1

hiku = 0
for i in range(n-2):
    s_i = s[i]
    for j in range(i+1, n-1):
        if s[j] == s_i: continue
        s_j = s[j]
        j_i = j-i
        if j+j_i < n:
            miru = s[j+j_i]
            if miru != s_i and miru != s_j:
                hiku += 1
        else:
            break

print(num_r*num_g*num_b-hiku)

Submission status: Accepted

Solution code:
def main():
    from itertools import accumulate

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

    R, G, B = [0], [0], [0]
    for s in S:
        if s == 'R':
            R.append(1)
            G.append(0)
            B.append(0)

        elif s == 'G':
            R.append(0)
            G.append(1)
            B.append(0)

        elif s == 'B':
            R.append(0)
            G.append(0)
            B.append(1)

    R = list(accumulate(R))
    G = list(accumulate(G))
    B = list(accumulate(B))

    # print(R)
    # print(G)
    # print(B)
    ans = 0
    for j in range(1, N - 1):
        sj = S[j]
        for i in range(j):
            si = S[i]
            sk = ''
            if j + j - i < N:
                sk = S[j + j - i]

            if si == sj:
                continue

            # if sj == sk:
            #     continue

            # print(sj, j, i)
            if (si == 'G' and sj == 'B') or (si == 'B' and sj == 'G'):
                ans += R[-1] - R[j + 1]
                if sk and si != sk and sj != sk:
                    ans -= 1
                # print('Rx', ans)

            if (si == 'R' and sj == 'B') or (si == 'B' and sj == 'R'):
                ans += G[-1] - G[j + 1]

                if sk and si != sk and sj != sk:
                    ans -= 1
                # print('Gx', ans)

            if (si == 'R' and sj == 'G') or (si == 'G' and sj == 'R'):
                ans += B[-1] - B[j + 1]
                if sk and si != sk and sj != sk:
                    ans -= 1
                # print('Bx', ans)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter

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

c = Counter(S)
ans = c["R"] * c["G"] * c["B"]

if ans == 0:
    print(0)
    exit()

for n_skip in range(1, N):
    for i in range(N):
        try:
            if S[i] != S[i+n_skip] and S[i+n_skip] != S[i + 2*n_skip] and S[i + 2*n_skip] != S[i]:
                ans -= 1
        except IndexError:
            break

print(ans)

Submission status: Accepted

Solution code:
a = int(input())
b = input()

import math

def nCr(n,r):
    f = math.factorial
    return f(n) // f(r) // f(n-r)


R = 0
G = 0
B = 0
for i in b:
    if i == "R":
        R += 1
    elif i == "G":
        G += 1
    else:
        B += 1


if R == 0 or G == 0 or B == 0:
    print(0)
else:
    res = 0
    for i in range(0, len(b)):
        for k in range(i + 1, len(b)):
            if (i + k) % 2 == 0:
                if b[i] != b[k] and b[i] != b[(i + k) //2] and b[k] != b[(i + k) //2]:
                    res += 1

    print(nCr(R, 1) * nCr(G, 1) * nCr(B, 1) - res)

Submission status: Accepted

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

R = set()
G = set()
B = set()
for i, s in enumerate(S):
    if s == "R":
        R.add(i)
    elif s == "G":
        G.add(i)
    else:
        B.add(i)

ans = len(R) * len(G) * len(B)

for a in R:
    for b in G:
        dif = b - a
        if b + dif in B:
            ans -= 1
        if a - dif in B:
            ans -= 1
        if dif % 2 == 0 and (a + b) // 2 in B:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

n = ni()
s = ns()

# RGBRGBGBBBB

r = [0] * (n + 1)
g = [0] * (n + 1)
b = [0] * (n + 1)

for i in range(n):
    r[i + 1] = r[i]
    g[i + 1] = g[i]
    b[i + 1] = b[i]
    if s[i] == 'R':
        r[i + 1] += 1
    elif s[i] == 'G':
        g[i + 1] += 1
    else:
        b[i + 1] += 1

ans = 0
for i in range(n):
    t = 0
    for j in range(i + 1, n):
        if s[i] != s[j]:
            if (s[i] == 'R' and s[j] == 'G') or (s[i] == 'G' and s[j] == 'R'):
                t += b[n] - b[j + 1]
            elif (s[i] == 'R' and s[j] == 'B') or (s[i] == 'B' and s[j] == 'R'):
                t += g[n] - g[j + 1]
            elif (s[i] == 'G' and s[j] == 'B') or (s[i] == 'B' and s[j] == 'G'):
                t += r[n] - r[j + 1]
    j = 1
    while i + j * 2 < n:
        if s[i] != s[i + j] and s[i] != s[i + j * 2] and s[i + j] != s[i + j * 2]:
            t -= 1
        j += 1
    ans += t

print(ans)

Submission status: Accepted

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

count = {"R": 0, "G": 0, "B": 0}
char2num = {"R": 1, "G": 10, "B": 100}
count_list = []

for char in S[::-1]:
    count[char] += 1
    count_list.append((count["R"], count["G"], count["B"]))
count_list = count_list[::-1]
        

ans = 0
for i in range(N-2):
    one = char2num[S[i]]
    for j in range(i+1, N-1):
        two = char2num[S[j]]
        if one != two:
            tmp = j+(j-i) < N
            if one+two == 11:
                if tmp and S[j+(j-i)] == "B":
                    ans += count_list[j][2] - 1
                else:
                    ans += count_list[j][2]
                    
            if one+two == 101:
                if tmp and S[j+(j-i)] == "G":
                    ans += count_list[j][1] - 1
                else:
                    ans += count_list[j][1]
                    
            if one+two == 110:
                if tmp and S[j+(j-i)] == "R":
                    ans += count_list[j][0] - 1
                else:
                    ans += count_list[j][0]
print(ans)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def c(i, j, k):
    return j - i != k - j


def main():
    N = I()
    s = S()
    # N = 2000
    # s = 'R' * 2000
    R = [0] * (N+1)
    G = [0] * (N+1)
    B = [0] * (N+1)

    for i in range(N):
        if s[i] == 'R':
            R[i] += 1
        elif s[i] == 'G':
            G[i] += 1
        elif s[i] == 'B':
            B[i] += 1
        R[i+1] = R[i]
        G[i+1] = G[i]
        B[i+1] = B[i]

    ans = 0
    for i in range(N):
        for j in range(i, N):
            if s[i] == 'R' and s[j] == 'G' or s[i] == 'G' and s[j] == 'R':
                nxt = j - i + j
                if nxt >= len(s):
                    ans += B[N] - B[j]
                elif s[nxt] != 'B':
                    ans += B[N] - B[j]
                else:
                    ans += B[N] - B[j]
                    ans -= 1
            elif s[i] == 'R' and s[j] == 'B' or s[i] == 'B' and s[j] == 'R':
                nxt = j - i + j
                if nxt >= len(s):
                    ans += G[N] - G[j]
                elif s[nxt] != 'G':
                    ans += G[N] - G[j]
                else:
                    ans += G[N] - G[j]
                    ans -= 1
            elif s[i] == 'B' and s[j] == 'G' or s[i] == 'G' and s[j] == 'B':
                nxt = j - i + j
                if nxt >= len(s):
                    ans += R[N] - R[j]
                elif s[nxt] != 'R':
                    ans += R[N] - R[j]
                else:
                    ans += R[N] - R[j]
                    ans -= 1


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


if __name__ == '__main__':
    main()

Submission status: Accepted

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

rgb_cnt = Counter(S)
ans = rgb_cnt["R"] * rgb_cnt["G"] * rgb_cnt["B"] 

for i in range(1,N-1):
    max_dist = min(i,N-i-1)
    m = S[i]
    for d in range(1,max_dist+1): # 中心からの距離
        l = S[i-d]
        r = S[i+d]
        if (l!=m and r!=m and l!= r):
            ans -= 1
print(ans)

Submission status: Accepted

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

    r_sums = [0] * N
    g_sums = [0] * N
    b_sums = [0] * N

    for i in range(N):
        r = 0
        g = 0
        b = 0
        if S[i] == 'R':
            r = 1
        if S[i] == 'G':
            g = 1
        if S[i] == 'B':
            b = 1
        
        if i == 0:
            r_sums[0] = r
            g_sums[0] = g
            b_sums[0] = b
        else:
            r_sums[i] = r_sums[i-1] + r
            g_sums[i] = g_sums[i-1] + g
            b_sums[i] = b_sums[i-1] + b

    ans = 0
    for i in range(N-2):
        for j in range(i,N-1):
            st = set([S[i],S[j]])
            if len(st) == 1:
                continue
            k_color = ""
            for color in ["R","G","B"]:
                if not color in st:
                    k_color = color
                    break
            
            sub = 0
            if 0 <= j+(j-i) < N:
                if S[j+(j-i)] == k_color:
                    sub = 1

            if k_color == "R":
                ans += r_sums[-1] - r_sums[j] - sub
            elif k_color == "G":
                ans += g_sums[-1] - g_sums[j] - sub
            elif k_color == "B":
                ans += b_sums[-1] - b_sums[j] - sub
    
    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

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

count=0
count_r=0
count_g=0
count_b=0

for s in S:
    if s=="G":
        count_g+=1
    elif s=="R":
        count_r+=1
    else:
        count_b+=1

for i in range((N-3)//2+1):
    #print(i)
    for j in range(N-(i*2)-2):
        #print("---")
        if S[j]==S[j+i+1] or S[j]==S[j+2*i+2] or S[j+i+1]==S[j+2*i+2]:
            pass
        else:
            count+=1

answer=count_g*count_r*count_b-count

print(answer)

Submission status: Accepted

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

r,g,b = 0,0,0
for k in range(n):
    if s[k] == "R":
        r += 1
    elif s[k] == "G":
        g += 1
    elif s[k] == "B":
        b += 1
# print(r,g,b,s)
d = 0

for p in range(0,n-2):
    q = 1 
    while p+2*q<=n-1:
        if s[p] != s[p+q] and s[p] != s[p+2*q] and s[p+q] != s[p+2*q]:
            d+=1
            # print(s[p],s[p+q],s[p+2*q])
            q += 1
            
            # print(q)
        else:
            # print(q)
            q = q+1

print(r*g*b-d)

Submission status: Accepted

Solution code:
import numpy as np


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


S_arr = np.array(list(S))

R_idx = np.where(S_arr == 'R')[0]
G_idx = np.where(S_arr == 'G')[0]
B_idx = np.where(S_arr == 'B')[0]

ans_cand = R_idx.shape[0] * G_idx.shape[0] * B_idx.shape[0]


for i in range(N-2):
    first = S[i]
    for j in range(i+1, N-1):
        second = S[j]
        sa = j - i
        k = j + sa
        if first == second:
            continue
        elif k >= N:
            break
        elif S[k] != first and S[k] != second:
            ans_cand -= 1

print(ans_cand)