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())
ss=input()
rs = set()
gs = set()
bs = set()
 
for i, s in enumerate(ss):
    if s == "R":
        rs.add(i)
    elif s == "G":
        gs.add(i)
    else:
        bs.add(i)
ans = 0
if len(gs) > len(bs) and len(gs) > len(rs):
    tmp = gs
    gs = bs
    bs = tmp
elif len(rs) > len(bs) and len(rs) > len(gs):
    tmp =rs
    rs = bs
    bs = tmp
    
for r in rs:
    for g in gs:
        c = 0
        if r+r-g in bs:
            c+=1
        if g+g-r in bs:
            c+=1
        if (g+r)/2 in bs:
            c+=1
        ans += len(bs) -c
print(ans)

Submission status: Accepted

Solution code:
import sys
from pprint import pprint

from collections import Counter
from math import factorial

def nCr(n, r):
    return factorial(n) // factorial(r) // factorial(n - r)

N = int(sys.stdin.readline())
S = sys.stdin.readline().strip()
# print(len(S))

counter = Counter(S)
if len(counter) != 3:
    print("0")
    sys.exit()
rgb_count = 0

max_width = len(S) // 2
for width in range(1, max_width+1):
    max_left = len(S) - 2 * width
    # print(width, max_left)
    for i in range(max_left):
        if len(set([S[i], S[i+width], S[i+2*width]])) == 3:
            rgb_count += 1


all_count = nCr(counter["R"], 1) * nCr(counter["G"], 1) * nCr(counter["B"], 1) 
# print(all_count, rgb_count)
print(all_count - rgb_count)

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())
ans = 0
R, G, B = 0, 0, 0

for char in S:
    if char == "R":
        R += 1
    elif char == "G":
        G += 1
    else:
        B += 1

ans = R*G*B

for i in range(len(S)):
    for j in range(i+1, len(S)):
        if S[i] != S[j]:
            i2j = j - i
            try:
                if not S[j+i2j] in [S[i], S[j]]:
                    ans -= 1
            except:
                break

print(ans)

Submission status: Accepted

Solution code:
def main():
    n=int(input())
    s=input()
    ans=0
    d=dict()
    dr=[0]*n
    dg=[0]*n
    db=[0]*n
    mr=[0]*n
    mg=[0]*n
    mb=[0]*n

    for i in range(n):
        if s[i]=='R':
            dr[i]=1
            mr[i]=1
        if s[i]=='G':
            dg[i]=1
            mg[i]=1
        if s[i]=='B':
            db[i]=1
            mb[i]=1

    for i in range(n-1):
        mr[n-2-i]+=mr[n-1-i]
        mg[n-2-i]+=mg[n-1-i]
        mb[n-2-i]+=mb[n-1-i]

    for i in range(n-2):
        for j in range(i,n-1):
            if s[i]==s[j]:
                continue
            if s[i]=='R' and s[j]=='G':
                k=1
            elif s[i]=='R' and s[j]=='B':
                k=2
            elif s[i]=='G' and s[j]=='R':
                k=1
            elif s[i]=='G' and s[j]=='B':
                k=0
            elif s[i]=='B' and s[j]=='R':
                k=2
            elif s[i]=='B' and s[j]=='G':
                k=0
            #print(k)
            
            if k==0:
                ans+=mr[j+1]
                if (j+(j-i))<n:
                    ans-=dr[j+(j-i)]
            if k==1:
                ans+=mb[j+1]
                if (j+(j-i))<n:
                    ans-=db[j+(j-i)]
            if k==2:
                ans+=mg[j+1]
                if (j+(j-i))<n:
                    ans-=dg[j+(j-i)]

    print(ans)
        



main()

Submission status: Accepted

Solution code:
#import re
import sys
input = sys.stdin.readline
#import heapq
#import bisect
#from collections import deque
#import math

def main():
    n = int(input())
    rgb = input()
    ans = 0
    for moji in ["RGB", "RBG", "BGR", "BRG", "GBR", "GRB"]:
        ans += search(moji, rgb)
    print(ans)

def search(moji, kensaku):
    n = len(kensaku)
    memo1 = []
    r = 0
    g = 0
    b = 0
    red = 0
    for i in range(n):
        if kensaku[i] == moji[0]:
            memo1.append(i)
        elif kensaku[i] == moji[1]:
            for num in memo1:
                check = num + 2 * (i - num)
                if check >= n:
                    continue
                else:
                    if kensaku[check] == moji[2]:
                        red += 1
    for i in range(n):
        if kensaku[i] == moji[0]:
            r += 1
        elif kensaku[i] == moji[1]:
            g += r
        elif kensaku[i] == moji[2]:
            b += g
    ans = b - red
    return ans
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python

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

    r = []
    g = []
    b = []

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

    count = len(r) * len(g) * len(b)
    for r_num in r:
        for g_num in g:
            dif = abs(r_num - g_num)
            i, j = tuple(sorted([r_num, g_num]))

            if i - dif > 0:
                if s[i - dif - 1] == 'B':
                    count -= 1
            if j + dif <= n:
                if s[j + dif - 1] == 'B':
                    count -= 1
            if dif % 2 == 0:
                if s [i + dif // 2 - 1] == 'B':
                    count -= 1

    print(count)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

s_l = {}
for i in range(N-1):
    t = {}
    s = S[i+1:]
    t['s'] = s
    t['R'] = s.count('R')
    t['G'] = s.count('G')
    t['B'] = s.count('B')
    s_l[i] = t

s = 0
for a in range(N-2):
    s1 = S[a]
    for b in range(a+1, N-1):
        s2 = S[b]
        if s1 == s2:
            continue
        n = s_l[b]['s']
        pat = ['R', 'G', 'B']
        pat.remove(s1)
        pat.remove(s2)
        count = s_l[b][pat[0]]
        d = b - a
        if len(n) > d-1 and n[d-1] == pat[0]:
            count -= 1
        s += count

print(s)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
if n<=3:
    print(0)
    exit()
r=set()
g=set()
b=set()
for i,c in enumerate(s):
    if c=='R':
        r.add(i)
    elif c=='G':
        b.add(i)
    else:
        g.add(i)
ans=0
lb=len(b)
for i in r:
    for j in g:
        t1=-1
        if abs(i-j)%2==0:
            t1=min(i,j)+abs(i-j)//2
        t2=max(i,j)+abs(i-j)
        t3=min(i,j)-abs(i-j)
        tc=0
        if t1 in b:
            tc+=1
        if t2 in b:
            tc+=1
        if t3 in b:
            tc+=1
        ans+=max(0,lb-tc)
print(ans)

Submission status: Accepted

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

dic = {"R":0, "G":0, "B":0}
for color in S:
    dic[color] += 1
count = dic["R"] * dic["G"] * dic["B"]

for step in range(1, (N - 1) // 2 + 1):
    for st in range(N - 2 * step):
        a, b, c = S[st], S[st + step], S[st + step * 2]
        if a != b and b != c and a != c:
            count -= 1
print(count)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
r = [0] * n
g = [0] * n
b = [0] * n
R, G, B = 0, 0, 0
for i in range(n - 1, -1, -1):
    if s[i] == 'R': R -= -1
    elif s[i] == 'G': G -= -1
    else: B -= -1
    r[i] = R
    g[i] = G
    b[i] = B
# print(r)
# print(g)
# print(b)

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

Submission status: Accepted

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

col_lis = [0 if c == "R" else 1 if c == "G" else 2 for c in S]

ans = 0

r_count = 0
g_count = 0
b_count = 0

color_table = []

for color in col_lis:
    if color == 0:
        r_count += 1
    elif color == 1:
        g_count += 1
    else:
        b_count += 1
    color_table.append([r_count, g_count, b_count])

ans = 0

for center in range(1, N - 1):
    for right in range(center + 1, N):
        if col_lis[right] == col_lis[center]:
            continue
        left = 3 - col_lis[right] - col_lis[center]
        ans += color_table[center - 1][left]
        if center * 2 - right >= 0 and col_lis[center * 2 - right] == left:
            ans -= 1


print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
r=[0]*n
g=[0]*n
b=[0]*n
for i in range(n):
    if s[i]=="R":
        r[i]+=1
    elif s[i]=="G":
        g[i]+=1
    elif s[i]=="B":
        b[i]+=1
import itertools as it
acr=list(it.accumulate(r))
acg=list(it.accumulate(g))
acb=list(it.accumulate(b))


ans=0
memo=set()
for j in range(n):
    if g[j]==1:
        ans+=acr[j]*(acb[-1]-acb[j])
        ans+=acb[j]*(acr[-1]-acr[j])
        for x in range(1,min(j,n-j-1)+1):
            if j-x>=0 and s[j-x]!=s[j+x] and s[j-x]!="G" and s[j+x]!="G":
                ans-=1
    if r[j]==1:
        ans+=acg[j]*(acb[-1]-acb[j])
        ans+=acb[j]*(acg[-1]-acg[j])
        for x in range(1,min(j,n-j-1)+1):
            if j-x>=0 and s[j-x]!=s[j+x] and s[j-x]!="R" and s[j+x]!="R":
                ans-=1
    if b[j]==1:
        ans+=acr[j]*(acg[-1]-acg[j])
        ans+=acg[j]*(acr[-1]-acr[j])
    
        for x in range(1,min(j,n-j-1)+1):
            if j-x>=0 and s[j-x]!=s[j+x] and s[j-x]!="B" and s[j+x]!="B":
                ans-=1

print(ans)

Submission status: Accepted

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n = ii()
s = input()

from bisect import bisect_left as bl
b = []
r = []
g = []
gg = 0
rr = 0
bb = 0
for i in range(n):

    if s[i] == "G":
        gg += 1
    elif s[i] == "B":
        bb += 1
    else:
        rr += 1
    
    r.append(rr)
    b.append(bb)
    g.append(gg)

brg = [b,r,g]
ans = 0
for i in range(1,n-1):
    if s[i] == "B":
        ima1 = 1
        ima2 = 2
    elif s[i] == "R":
        ima1 = 0
        ima2 = 2
    else:
        ima1 = 0
        ima2 = 1
    ans += brg[ima1][i-1]*(brg[ima2][n-1]- brg[ima2][i])
    ans += brg[ima2][i-1]*(brg[ima1][n-1]- brg[ima1][i])
for i in range(1,n-1):
    for k in range(i):
        tmp = i-k
        if i + tmp > n-1:
            continue
        if s[k] == s[i]:
            continue
        if s[i] == s[i+tmp]:
            continue
        if s[k] == s[i+tmp]:
            continue
        ans -= 1

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
S=input()
X=[[0]*(N+1) for i in range(3)]
d={'R':0,'G':1,'B':2}
for i,s in enumerate(S):
  X[d[s]][i]+=1
  X[0][i+1]=X[0][i]
  X[1][i+1]=X[1][i]
  X[2][i+1]=X[2][i]
ans=0
for i,s in enumerate(S):
  _=1
  for j in range(3):
    if d[s]==j:
      continue
    _*=X[j][-1]-X[j][i]
  ans+=_
for i in range(1,(N+1)//2):
  j=0
  while j+2*i<N:
    if S[j]!=S[j+i] and S[j]!=S[j+2*i] and S[j+i]!=S[j+2*i]:
      ans-=1
    j+=1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = str(input())
r = s.count("R")
g = s.count("G")
b = s.count("B")
total = r * g * b
for i in range(2000):
    for j in range(n-2*i):
        if j + (2*i) <= n-1:
            if s[j] != s[j+i] and s[j+i] != s[j+(2*i)] and s[j+(2*i)] != s[j]:
                total -= 1
print(total)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import defaultdict


def main():
    n = int(input().strip())
    s = input().strip()

    pos = defaultdict(set)
    for i, c in enumerate(s):
        pos[c].add(i)

    # ありえるくみあわせを求める
    base = len(pos["R"]) * len(pos["G"]) * len(pos["B"])

    # 条件2にあてはまる分を求める
    sk = sorted(["R", "G", "B"], key=lambda k: len(pos[k]))
    for p1 in pos[sk[0]]:
        for p2 in pos[sk[1]]:
            p_min, p_max = (p1, p2) if p1 < p2 else (p2, p1)
            if p_min - (p_max - p_min) in pos[sk[2]]:
                base -= 1
            if p_max + (p_max - p_min) in pos[sk[2]]:
                base -= 1
            if (p_max + p_min) % 2 == 0 and (p_max + p_min) // 2 in pos[sk[2]]:
                base -= 1

    print(base)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import collections

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

c = collections.Counter(s)

ans_count = c['R'] * c['G'] * c['B']

for i in range(1, (n+1)//2):
    for j in range(n):
        if j+(2*i) >= n:
            break

        if s[j] != s[j+i] and s[j+i] != s[j+(2*i)] and s[j] != s[j+(2*i)]:
            ans_count -= 1


print(ans_count)

Submission status: Accepted

Solution code:
import math

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

minuscount=0
for i in range(n-2):
    a=i+1
    for j in range(i+1,math.floor(n/2 + a/2)):
        b=j+1
        a1=s[i]
        a2=s[j]
        a3=s[2*b-a-1]
        if a1!=a2 and a2!=a3 and a1!=a3:
            minuscount+=1

rcount=s.count("R")
gcount=s.count("G")
bcount=s.count("B")

print(rcount*gcount*bcount-minuscount)

Submission status: Accepted

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

for c in S:
    if c == 'R':
        r += 1
    elif c == 'G':
        g += 1
    else:
        b += 1

ans = r * g * b

cnt = 0
for d in range(1, (N - 3) // 2 + 1 + 1):
    i = 0
    while i + 2 * d < N:
        if not (S[i] == S[i + d]) and  not (S[i + d] == S[i + 2*d]  ) and not (S[i + 2 * d] == S[i]):
            cnt += 1
        i += 1

ans -= cnt

print(ans)

Submission status: Accepted

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

nr = S.count("R")
ng = S.count("G")
nb = S.count("B")

exp = 0
for i in range(N-2):
    for d in range(1,(N-1-i)//2+1):
        if S[i] !=S[i+d] and S[i+d] != S[i+2*d] and S[i] != S[i+2*d]:
            exp = exp +1

print(nr*ng*nb-exp)

Submission status: Accepted

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

nowR = s.count("R")
nowG = s.count("G")
nowB = s.count("B")

ans = 0
for i in range(n-1):
    R = nowR
    G = nowG
    B = nowB
    now = s[i]
    if now == "R":
        R -= 1
    elif now == "G":
        G -= 1
    else:
        B -= 1
    nowR = R
    nowG = G
    nowB = B
    for j in range(i+1,n):
        now2 = s[j]
        if now == "R":
            if now2 == "G":
                G -= 1
                ans += B
                if 2*j-i < n and s[2*j-i] == "B":
                    ans -= 1
            elif now2 == "B":
                B -= 1
                ans += G
                if 2*j-i < n and s[2*j-i] == "G":
                    ans -= 1
        elif now == "G":
            if now2 == "R":
                R -= 1
                ans += B
                if 2*j-i < n and s[2*j-i] == "B":
                    ans -= 1
            elif now2 == "B":
                B -= 1
                ans += R
                if 2*j-i < n and s[2*j-i] == "R":
                    ans -= 1
        elif now == "B":
            if now2 == "G":
                G -= 1
                ans += R
                if 2*j-i < n and s[2*j-i] == "R":
                    ans -= 1
            elif now2 == "R":
                R -= 1
                ans += G
                if 2*j-i < n and s[2*j-i] == "G":
                    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
RGB = ['R', 'G', 'B']
import collections
if len(set(list(S))) <= 2:
    print(0)
else:
    dct = dict(collections.Counter(S))

    cnt = 0
    for i in range(N-2):
        for k in range((N - 1 - i) // 2 + 1):
            temp = {S[i], S[i + k], S[i + k * 2]}
            if len(temp) == 3:
                cnt += 1
            #print(cnt)
    print(dct['R'] * dct['G'] * dct['B'] - cnt)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
from collections import Counter
def MI():return map(int,input().split())
def LI():return list(MI())

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


for j in range(n):
    jj=s[j]
    for i in range(j):
        k=2*j-i
        if not j<=k<=n-1:
            continue
        ii=s[i]
        kk=s[k]
        if jj!=ii and jj!=kk and ii!=kk:
            ans-=1

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
S=input()
R=[0]*N
G=[0]*N
B=[0]*N

for i in range(N):
    if S[i]=="R":
        R[i]=1
    elif S[i]=="G":
        G[i]=1
    else:
        B[i]=1
R_S=[0]*N
G_S=[0]*N
B_S=[0]*N
R_S[0] = R[0]
G_S[0] = G[0]
B_S[0] = B[0]
for i in range(1,N):
    R_S[i]=R_S[i-1]+R[i]
    G_S[i]=G_S[i-1]+G[i]
    B_S[i]=B_S[i-1]+B[i]

ans=0
for j in range(1,N-1):
    char=S[j]
    if char=="G":
        ans += R_S[j-1]*(B_S[N-1]-B_S[j])
        ans += B_S[j-1]*(R_S[N-1]-R_S[j])
        min_len=min(j,N-1-j)
        for i in range(1,min_len+1):
            if (S[j-i]=="R" and S[j+i]=="B") or (S[j-i]=="B" and S[j+i]=="R"):
                ans -= 1
    if char=="R":
        ans += G_S[j-1]*(B_S[N-1]-B_S[j])
        ans += B_S[j-1]*(G_S[N-1]-G_S[j])
        min_len=min(j,N-1-j)
        for i in range(1,min_len+1):
            if (S[j-i]=="G" and S[j+i]=="B") or (S[j-i]=="B" and S[j+i]=="G"):
                ans -= 1
    if char=="B":
        ans += G_S[j-1]*(R_S[N-1]-R_S[j])
        ans += R_S[j-1]*(G_S[N-1]-G_S[j])
        min_len=min(j,N-1-j)
        for i in range(1,min_len+1):
            if (S[j-i]=="G" and S[j+i]=="R") or (S[j-i]=="R" and S[j+i]=="G"):
                ans -= 1
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)  # 再帰関数の再帰の深さを設定
to_index = lambda x: int(x) - 1  # 入力した数字に1を引いたものを返す
print_list_in_2D = lambda x: print(*x, sep="\n")  # リストの要素を改行を挟んで表示する関数

# 入力を整数に変換して受け取る
def input_int():
    return int(input())

def map_int_input():
    return map(int, input())

MII = map_int_input

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

def MII_to_index():
    return map(to_index, input())

def MII_split_to_index():
    return map(to_index, input().split())

# 入力全てを整数に変換したものの配列を受け取る
def list_int_inputs():
    return list(map(int, input()))

LII = list_int_inputs

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

# 2次元リスト化
def LII_2D(rows_number):
    return [LII() for _ in range(rows_number)]

def LII_split_2D(rows_number):
    return [LII_split() for _ in range(rows_number)]

N = input_int()
S = input()

if N < 3:
    print(0)
    exit()
rs = []
gs = []
bs = []
for i in range(len(S)):
    if S[i] == 'R':
        rs.append(i)
    elif S[i] == 'G':
        gs.append(i)
    else:
        bs.append(i)
count = len(rs) * len(gs) * len(bs)
# for r in rs:
#     for g in gs:
#         for b in bs:
#             rgb = [r, g, b]
#             rgb.sort()
#             if rgb[1]-rgb[0] != rgb[2]-rgb[1]:
#                 count += 1

for skip in range(1, N // 2 + 1):
    for i in range(N - 2):
        if i + 2 * skip > N - 1:
            break
        elif S[i] == S[i + skip] or S[i + skip] == S[i + 2 * skip] or S[i] == S[i + 2 * skip]:
            continue
        else:
            count -= 1

print(count)

Submission status: Accepted

Solution code:
from collections import defaultdict
n = int(input())
S = input()
patterns = ["RGB","RBG","GBR","GRB","BRG","BGR"]
acc  = [ [0] * (n + 1) for _ in range(n+1)]

ans = 0
for pattern in patterns:
    c1 = pattern[0]
    c2 = pattern[1]
    c3 = pattern[2]
    cands = []
    #i c1の位置で
    for i1 in range(n):
        for i2 in range(i1 + 1,n):
            if S[i1] == c2 and S[i2] == c3:
                cands.append((i1,i2-i1))
    # anss[i1][i2-i1]→左をi1に固定したときの、距離i2-i1の組の個数
    cands.reverse()
    di = defaultdict(lambda :set())
    for cand in cands:
        left,dist = cand
        di[left].add(dist)
    acc = [0]
    for i in range(1,n):
        acc.append(acc[i-1] + len(di[i]))

    for  i in range(0,n):
        if S[i] == c1:
            ans += acc[n - 1] -acc[i]
            for i2 in range(i + 1,n):
                if i2 - i in di[i2]:
                    ans -=1
print(ans)

Submission status: Accepted

Solution code:
import copy

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

RL = [0]*(N+1)
GL = copy.deepcopy(RL)
BL = copy.deepcopy(RL)
R = []
G = []
B = []
for i in range(N):
    if S[i] == 'R':
        R.append(i+1)
        RL[i+1] = 1
    elif S[i] == 'G':
        G.append(i+1)
        GL[i+1] = 1
    elif S[i] == 'B':
        B.append(i+1)
        BL[i+1] = 1

len_r = len(R)
len_g = len(G)
len_b = len(B)
ans = 0
if max(len_r, len_g, len_b) == len_b:
    for i in range(len_r):
        for j in range(len_g):
            ans += len_b
            tmp_abs = abs(R[i]-G[j])

            index = (min(R[i], G[j])-tmp_abs)
            if index > 0 and BL[index] == 1:
                ans -= 1

            index = (max(R[i], G[j])+tmp_abs)
            if index <= N and BL[index] == 1:
                ans -= 1

            if tmp_abs % 2 == 0 and BL[max(R[i], G[j])-(tmp_abs//2)] == 1:
                ans -= 1

elif max(len_r, len_g, len_b) == len_g:
    for i in range(len_r):
        for j in range(len_b):
            ans += len_g
            tmp_abs = abs(R[i]-B[j])

            index = (min(R[i], B[j])-tmp_abs)
            if index > 0 and GL[index] == 1:
                ans -= 1

            index = (max(R[i], B[j])+tmp_abs)
            if index <= N and GL[index] == 1:
                ans -= 1

            if tmp_abs % 2 == 0 and GL[max(R[i], B[j])-(tmp_abs//2)] == 1:
                ans -= 1

else:
    for i in range(len_g):
        for j in range(len_b):
            ans += len_r
            tmp_abs = abs(G[i]-B[j])

            index = (min(G[i], B[j])-tmp_abs)
            if index > 0 and RL[index] == 1:
                ans -= 1

            index = (max(G[i], B[j])+tmp_abs)
            if index <= N and RL[index] == 1:
                ans -= 1

            if tmp_abs % 2 == 0 and RL[max(G[i], B[j])-(tmp_abs//2)] == 1:
                ans -= 1
print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
printV = lambda x: print(*x, sep="\n")
printH = lambda x: print(" ".join(map(str,x)))
def IS(): return sys.stdin.readline()[:-1]
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LII(rows_number): return [II() for _ in range(rows_number)]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]

def main():
	n = II()
	s = IS()
	r,g,b=[],[],[]

	def binary_search(lst, K):
		l = 0; r = len(lst);
		while(l+1<r):
			mid = (l+r)//2
	    #下記の操作を書き換えることによって探索条件を変更可能
			if(lst[mid]>K): r=mid
			else: l=mid
		return l

	for i,ss in enumerate(s):
		if ss=='R':
			r.append(i)
		elif ss=='G':
			g.append(i)
		else:
			b.append(i)
	ans=len(r)*len(g)*len(b)
	for rr in r:
		for gg in g:
			a=max(rr,gg)+abs(rr-gg)
			if(a<n):
				if(s[a]=="B"):
					ans-=1
			a=min(rr,gg)-abs(rr-gg)
			if(a<n and a>=0):
				if(s[a]=="B"):
					ans-=1
			if((rr+gg)%2==0):
				a=(rr+gg)//2
				if(a<n):
					if(s[a]=="B"):
						ans-=1
	print(ans)







if __name__ == '__main__':
	main()

Submission status: Accepted

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

rgb = [[S.count('R'), S.count('G'), S.count('B')]]

if S[0] == 'R':
    rgb[0][0] -= 1
elif S[0] == 'G':
    rgb[0][1] -= 1
else:
    rgb[0][2] -= 1

for i in range(1, n):
    r, g, b = rgb[i-1][0], rgb[i-1][1], rgb[i-1][2]
    if S[i] == 'R':
        r -= 1
    elif S[i] == 'G':
        g -= 1
    else:
        b -= 1
    rgb.append([r, g, b])

ans = 0

for i in range(n-2):
    for j in range(i+1, n-1):
        if (S[i] == 'R' and S[j] == 'G') or (S[i] == 'G' and S[j] == 'R'):
            if 2*j-i < n and S[2*j-i] == 'B':
                ans += rgb[j][2] - 1
            else:
                ans += rgb[j][2]
        elif (S[i] == 'R' and S[j] == 'B') or (S[i] == 'B' and S[j] == 'R'):
            if 2*j-i < n and S[2*j-i] == 'G':
                ans += rgb[j][1] - 1
            else:
                ans += rgb[j][1]
        elif (S[i] == 'G' and S[j] == 'B') or (S[i] == 'B' and S[j] == 'G'):
            if 2*j-i < n and S[2*j-i] == 'R':
                ans += rgb[j][0] - 1
            else:
                ans += rgb[j][0]

print(ans)

Submission status: Accepted

Solution code:
import sys,math,copy,queue,itertools,bisect
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
_LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.readline())

N = NI()
S = input()
R = []
G = []
B = []
cnt = 0
for b in range(N-1,-1,-1):
    if S[b] == 'R':
        cnt += 1
    R.append(cnt)
R.reverse()
cnt = 0
for b in range(N-1,-1,-1):
    if S[b] == 'G':
        cnt += 1
    G.append(cnt)
G.reverse()
cnt = 0
for b in range(N-1,-1,-1):
    if S[b] == 'B':
        cnt += 1
    B.append(cnt)
B.reverse()

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

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

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

print (ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
r = 0
g = 0
b = 0
rg = 0
gb = 0
br = 0
rgb = 0
for i in range(n):
    if s[i] == 'R':
        r+=1
        rg+=g
        br+=b
        rgb+=gb
    elif s[i] == 'G':
        g+=1
        rg+=r
        gb+=b
        rgb+=br
    else:
        b+=1
        br+=r
        gb+=g
        rgb+=rg

for i in range(n):
    for j in range(i+1, n):
        k = j+(j-i)
        if k>=n: break
        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            rgb-=1
print(rgb)

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):
    mid = s[i]
    front = s[i-1::-1]
    back = s[i+1:]
    for j in range(min(len(front),len(back))):
        if mid != front[j] and mid != back[j] and front[j] != back[j]:
            ans -= 1
    
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
r = s.count("R")
g = s.count("G")
b = s.count("B")
c = 0
for i in range(n):
    for j in range(1,int((n-i-1)/2)+1):
        if len(set([s[i],s[i+j],s[i+j+j]])) == 3:
            c += 1
print((r*g*b) - c)

Submission status: Accepted

Solution code:


############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
    return(int(input().rstrip()))
def inlt():
    return(list(map(int,input().rstrip().split())))
def insr():
    s = input().rstrip()
    return(s[:len(s) - 1])
def invr():
    return(map(int,input().rstrip().split()))
################################################################
n = int(raw_input())
s = raw_input()
con = {'R':0,'B':1,'G':2}
r_dict = [[0, 0, 0] for i in range(n)]
r_dict[n - 1][con[s[n - 1]]] = 1
for i in range(n - 2,-1,-1):
    for j in range(3):
        r_dict[i][j] = r_dict[i + 1][j]
    r_dict[i][con[s[i]]] += 1
ans = 0
for i in range(n):
    f = s[i]
    for j in range(i + 1,n):
        if s[j] != s[i]:
            se = s[j]
            gap = j - i
            if 'R' != f and 'R' !=se:
                th= 'R'
            elif 'B' != f and 'B' != se:
                th = 'B'
            else:
                th = 'G'
            #print(f,se,th,i,j)
            ans += r_dict[j][con[th]]
            if j + gap < n and s[j + gap] == th:
                ans -= 1
        
print ans
#print('No')
#print()

Submission status: Accepted

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

# それぞれのインデック格納
r=[]
b=[]
g=[]

for i in range(n):
    if s[i]=='R':
        r.append(i)
    elif s[i]=='B':
        b.append(i)
    else:
        g.append(i)

ans=0
q=len(g)
if q==0:
    print(0)
    exit()

for i in range(len(r)):
    for j in range(len(b)):
        if r[i]<b[j]:
            x=b[j]+b[j]-r[i]
            y=r[i]-(b[j]-r[i])
        else:
            x=r[i]+r[i]-b[j]
            y=b[j]-(r[i]-b[j])

        if 0<=x and x<=n-1:
            z=bisect.bisect_right(g,x)-1
            if g[z]==x:
                ans-=1
        if 0<=y and y<=n-1:
            z=bisect.bisect_right(g,y)-1
            if g[z]==y:
                ans-=1
        if (r[i]+b[j])%2==0 and 0<=(r[i]+b[j])//2 and (r[i]+b[j])//2<=n-1:
            w=(r[i]+b[j])//2
            z=bisect.bisect_right(g,w)-1
            if g[z]==w:
                ans-=1
        ans+=q
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=list(input())
r=0
g=0
b=0
for c in s:
    if c=='R':
        r+=1
    elif c=='G':
        g+=1
    else:
        b+=1
u=0
m=(n-1)//2
for c in range(1,m+1):
    for d in range(n-2*c):
        w={s[d],s[d+c],s[d+2*c]}
        if len(w)==3:
            u-=1
u+=r*g*b
print(u)

Submission status: Accepted

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

r = S.count('R')
g = S.count('G')
b = S.count('B')
RGB = set(['R', 'G', 'B'])

exclude = 0
for d in range(1, N // 2 + 1):
    for i in range(N - 2 * d):
        if set([S[i], S[i + d], S[i + 2 * d]]) == RGB:
            exclude += 1
ans = r * g * b
print(ans - exclude)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
r = []
g = []
b = []
n_r = n_g = n_b = 0

for i in range(N):
    if S[i] == "R":
        r.append(i)
        n_r += 1
    elif S[i] == "G":
        g.append(i)
        n_g += 1
    else:
        b.append(i)
        n_b += 1

all = n_r*n_b*n_g

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