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 = input()
listR = []
listB = []
listG = []
numR = 0
numG = 0
numB = 0

for idx,i in enumerate(S):
    if i == 'R':
        numR += 1
        listR.append((idx, numR, numG, numB))
    elif i == 'G':
        numG += 1
        listG.append((idx, numR, numG, numB))
    else:
        numB += 1
        listB.append((idx, numR, numG, numB))

result = 0
patterns = [
    (listR, listG, (3, "B", numB)),
    (listR, listB, (2, "G", numG)),
    (listG, listR, (3, "B", numB)),
    (listG, listB, (1, "R", numR)),
    (listB, listG, (1, "R", numR)),
    (listB, listR, (2, "G", numG)),
]
#Si = R
for list1, list2, str3 in patterns:
    for datR in list1:
        for dat2 in list2:
            idx = dat2[0]
            if idx > datR[0]:
                result += str3[2] - dat2[str3[0]]
                k = idx + (idx - datR[0])
                if k < N and S[k] == str3[1]:
                    result -= 1
print(result)

Submission status: Accepted

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

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

a = 0
for i in range(n):
    d = 1
    while i+2*d <= n-1:
        if s[i] != s[i+d] and s[i+d] != s[i+2*d] and s[i] != s[i+2*d]:
            a += 1
        d += 1

print (count['R']*count['G']*count['B'] - a)

Submission status: Accepted

Solution code:
N=int(input())
S=list(input())
rc,bc,gc=[0]*N,[0]*N,[0]*N
if S[0]=="R":
  rc[0]+=1
elif S[0]=="B":
  bc[0]+=1
if S[0]=="G":
  gc[0]+=1
for i in range(1,N):
  if S[i]=="R":
    rc[i]=rc[i-1]+1
    bc[i]=bc[i-1]
    gc[i]=gc[i-1]
  elif S[i]=="B":
    bc[i]=bc[i-1]+1
    gc[i]=gc[i-1]
    rc[i]=rc[i-1]
  elif S[i]=="G":
    gc[i]=gc[i-1]+1    
    rc[i]=rc[i-1]
    bc[i]=bc[i-1]

ans=0
for i in range(N-2):
  for j in range(i+1,N-1):
    if S[i]==S[j]:
      pass
    else:
      if [S[i],S[j]]==["R","B"] or [S[i],S[j]]==["B","R"]:
        ans+=gc[-1]-gc[j]
        if 2*j-i<N:
          if S[2*j-i]=="G":
            ans-=1
      elif [S[i],S[j]]==["B","G"] or [S[i],S[j]]==["G","B"]:
        ans+=rc[-1]-rc[j]
        if 2*j-i<N:
          if S[2*j-i]=="R":
            ans-=1
      elif [S[i],S[j]]==["G","R"] or [S[i],S[j]]==["R","G"]:
        ans+=bc[-1]-bc[j]
        if 2*j-i<N:
          if S[2*j-i]=="B":
            ans-=1
            
print(ans)

Submission status: Accepted

Solution code:
import sys
import math
import fractions
from collections import deque
from collections import defaultdict
sys.setrecursionlimit(10**7)

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

r_sum = [0] * N
g_sum = [0] * N
b_sum = [0] * N

if S[0] == "R":
    r_sum[0] = 1
elif S[0] == "G":
    g_sum[0] = 1
else:
    b_sum[0] = 1

c_map = {"R": 1, "G": 2, "B": 3}

for i, c in enumerate(S):
    if i == 0:
        continue
    r_sum[i] = r_sum[i-1]
    g_sum[i] = g_sum[i-1]
    b_sum[i] = b_sum[i-1]
    if c == "R":
        r_sum[i] += 1
    elif c == "G":
        g_sum[i] += 1
    else:
        b_sum[i] += 1

ans = 0
for i in range(N):
    for j in range(i+1, N):
        d = j - i
        if S[i] != S[j]:
            rest = 6 - c_map[S[i]] - c_map[S[j]]
            if rest == 1:
                ans += r_sum[N - 1] - r_sum[j]
                if j + d <= N - 1 and c_map[S[j + d]] == 1:
                    ans -= 1
            elif rest == 2:
                ans += g_sum[N - 1] - g_sum[j]
                if j + d <= N - 1 and c_map[S[j + d]] == 2:
                    ans -= 1
            else:
                ans += b_sum[N - 1] - b_sum[j]
                if j + d <= N - 1 and c_map[S[j + d]] == 3:
                    ans -= 1

print(ans)

Submission status: Accepted

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

r=g=b=0
c=0

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

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

print(r*g*b-c)

Submission status: Accepted

Solution code:
N = int(input())

colormap = {'R':0,'G':1,'B':2}
S = [colormap[c] for c in input()]

bads = 0
for i in range(N):
    for s in range(1,(N-i+1)//2):
        bads += int(S[i]^S[i+s]^S[i+2*s] == 3)

totals = [0]*3
for c in S:
    totals[c] += 1

print(totals[0]*totals[1]*totals[2] - bads)

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())
s_r = []
s_g = []
s_b = []

for i in range(len(S)):
    if S[i] == 'R':
        s_r.append(i)
    elif S[i] == 'G':
        s_g.append(i)
    elif S[i] == 'B':
        s_b.append(i)

N = len(s_r)*len(s_g)*len(s_b)

s_b = set(s_b)
for i in range(len(s_r)):
    for j in range(len(s_g)):
        M = max(s_r[i],s_g[j])
        m = min(s_r[i],s_g[j])
        if M+(M-m) in s_b:
            N -= 1

        if (M-m) %2 == 0:
            if m + (M-m)//2 in s_b:
                N -= 1

        if m-(M-m) in s_b:
            N -= 1

print(N)

Submission status: Accepted

Solution code:
import bisect
n = int(input())
S = input()
r = []
g = []
b = []
for i, s in enumerate(S):
    if s == "R":
        r.append(i)
    elif s == "G":
        g.append(i)
    else:
        b.append(i)

# print(s, r, g, b)
ans = len(r) * len(g) * len(b)
i = 0
j = 1
while i + 2 * j < n:
    while i + 2 * j < n:
        if S[i] != S[i + j] != S[i + 2 * j] != S[i]:
            ans -= 1
        i += 1
    j += 1
    i = 0

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(700000)

def s_in():
    return input()

def n_in():
    return int(input())

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

def print_l(l):
    print(' '.join(map(str, l)))

class Interval():
    def __init__(self, li):
        self.li = li
        self.n = len(li)
        self.sum_li = [li[0]]
        for i in range(1, self.n):
            self.sum_li.append(self.sum_li[i-1] + li[i])

    def sum(self, a, b=None):
        if b is None:
            return self.sum(0, a)

        res = self.sum_li[min(self.n-1, b-1)]
        if a > 0:
            res -= self.sum_li[a-1]
        return res

n = n_in()
s = s_in()


from collections import Counter

c=Counter(s)

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


for i in range(n):
    d = 1
    while i+d+d < n:
        if s[i] != s[i+d] and s[i+d] != s[i+d+d] and s[i] != s[i+d+d]:
            res -= 1

        d += 1
    

print(res)

Submission status: Accepted

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

r=0
ListR = []
g=0
ListG = []
b=0
ListB = []
for i in range(N):
    if S[i] == 'R':
        r = r+1
        ListR.append(i)
    elif S[i] == 'G':
        g = g+1
        ListG.append(i)
    else:
        b = b+1
        ListB.append(i)
        
n = (N+1)//2
  
remove = 0
for i in range(1,n+1):
    for j in range(N-2*i):
        if S[j] != S[j+i] and S[j+i] != S[j+2*i] and S[j] != S[j+2*i]:
            remove = remove+1
            
print(r*g*b-remove)

Submission status: Accepted

Solution code:
import sys
from collections import *
import heapq
import math
from math import gcd
import bisect
import copy
from itertools import permutations,accumulate,combinations,product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n=int(input())
s=input()
dic={"R":[],"G":[],"B":[]}
for i in range(n):
    if not s[i] in dic:
        dic[s[i]]=[i]
    else:
        dic[s[i]].append(i)
# print(dic)
se=set(dic["B"])
# print(se)
ans=len(dic["R"])*len(dic["G"])*len(dic["B"])
for i in range(len(dic["R"])):
    for j in range(len(dic["G"])):
        l,r=min(dic["R"][i],dic["G"][j]),max(dic["R"][i],dic["G"][j])
        if r+(r-l) in se:
            ans-=1
        if l-(r-l) in se:
            ans-=1
        if (r-l)%2==0 and l+(r-l)//2 in se:
            ans-=1
print(ans)

Submission status: Accepted

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

idxs = [[] for _ in range(3)]
for i in range(N):
    if S[i] == 'R':
        idxs[0].append(i)
    elif S[i] == 'G':
        idxs[1].append(i)
    else:
        idxs[2].append(i)

import itertools
import bisect

ans = 0
for ch in itertools.permutations(range(3)):
    for idx_a in idxs[ch[0]]:
        for idx_b in idxs[ch[1]]:
            if idx_b < idx_a: continue
            pos_c = bisect.bisect_left(idxs[ch[2]], idx_b)
            pos_ex = bisect.bisect_left(idxs[ch[2]], 2 * idx_b - idx_a)
            #
            ans_tmp = len(idxs[ch[2]]) - pos_c
            if pos_ex < len(idxs[ch[2]]) and idxs[ch[2]][pos_ex] == 2 * idx_b - idx_a:
                ans_tmp = max(0, ans_tmp - 1)
            #
            ans += ans_tmp

print(ans)

Submission status: Accepted

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

R = 0
G = 0
B = 0
ans = 0
for i in range(N):
    if S[i] == 'R':
        R += 1
        ans += G * B
    elif S[i] == 'G':
        G += 1
        ans += R * B
    elif S[i] == 'B':
        B += 1
        ans += R * G


L = 1
while L * 2 + 1 <= N:
    for i in range(N - L * 2):
        Q = [S[i], S[i + L], S[i + L + L]]
        if len(set(Q)) == 3:
            ans -= 1
    L += 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
R = set()
G = set()
B = set()
for i in range(n):
    if s[i] == 'R':
        R.add(i)
    elif s[i] == 'B':
        B.add(i)
    else:
        G.add(i)
ans = 0
for r in R:
    for g in G:
        ans += len(B)
        if 2*r - g in B:
            ans -= 1
        if 2*g - r in B:
            ans -= 1
        if not (r+g)&1 and (r+g)//2 in B:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n=int(input())
s=list(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)
r=set(r)
g=set(g)
b=set(b)
for i in r:
    for j in g:
        if (i+j)%2==0 and ((i+j)//2 in b):
            ans-=1
for i in r:
    for j in b:
        if (i+j)%2==0 and ((i+j)//2 in g):
            ans-=1
for i in b:
    for j in g:
        if (i+j)%2==0 and ((i+j)//2 in r):
            ans-=1
print(ans)

Submission status: Accepted

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

if n == 1 or n == 2:
    print(0)
    exit()

l = [[0, 0, 0] for i in range(n+1)]
r = [[0, 0, 0] for i in range(n+1)]
for i in range(n):
    if s[i] == 'R':
        l[i+1][0] = l[i][0] +1
        l[i+1][1] = l[i][1]
        l[i+1][2] = l[i][2]
    elif s[i] == 'G':
        l[i+1][0] = l[i][0]
        l[i+1][1] = l[i][1] +1
        l[i+1][2] = l[i][2]
    else:
        l[i+1][0] = l[i][0]
        l[i+1][1] = l[i][1]
        l[i+1][2] = l[i][2] +1

s.reverse()
for i in range(n):
     if s[i] == 'R':
         r[i+1][0] = r[i][0] +1
         r[i+1][1] = r[i][1]
         r[i+1][2] = r[i][2]
     elif s[i] == 'G':
         r[i+1][0] = r[i][0]
         r[i+1][1] = r[i][1] +1
         r[i+1][2] = r[i][2]
     else:
         r[i+1][0] = r[i][0]
         r[i+1][1] = r[i][1]
         r[i+1][2] = r[i][2] +1

#print(l)
r.reverse()
#print(r)

s.reverse()
ans = 0
for i in range(1, n-1):
    if s[i] == 'R':
        ans += l[i][1]*r[i+1][2]
        ans += l[i][2]*r[i+1][1]
    elif s[i] == 'G':
        ans += l[i][0]*r[i+1][2]
        ans += l[i][2]*r[i+1][0]
    else:
        ans += l[i][0]*r[i+1][1]
        ans += l[i][1]*r[i+1][0]
    for j in range(1, i+1):
        if i+j <= n-1:
            if s[i-j] != s[i] and s[i+j] != s[i] and s[i-j] != s[i+j]:
                ans -= 1
print(ans)

Submission status: Accepted

Solution code:
def read():
    N = int(input())
    S = input()
    return N, S

def solve(N, S, NMAX=4000):
    bucket = [0, 0, 0]
    for i in range(N):
        if S[i] == 'R':
            bucket[0] += 1
        elif S[i] == 'G':
            bucket[1] += 1
        elif S[i] == 'B':
            bucket[2] += 1
    ans = bucket[0] * bucket[1] * bucket[2]
    for i in range(N-2):
        for j in range(i+1, N-1):
            k = j + j - i
            if k >= N:
                continue
            if S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:
                ans -= 1
    return ans

if __name__ == '__main__':
    inputs = read()
    print("{}".format(solve(*inputs)))

Submission status: Accepted

Solution code:
n = int(input())
s = input()
r_num = len([x for x in s if x == 'R'])
g_num = len([x for x in s if x == 'G'])
b_num = n - r_num - g_num
ans = r_num * g_num * b_num
for interval in range(0, (n - 3) // 2 + 1):
    for left_index in range(0, n - (2 * interval + 3) + 1):
        letter0 = s[left_index]
        letter1 = s[left_index + interval + 1]
        letter2 = s[left_index + 2 * interval + 2]
        if len(set([letter0, letter1, letter2])) == 3:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
rgb = list(input())
rc, gc, bc = rgb.count('R'), rgb.count('G'), rgb.count('B')
c=rc*gc*bc
for i in range(n-2):
    for j in range(i+1, n-1):
        if rgb[i]!=rgb[j]:
            k = 2*j-i
            if k <= n-1:
                if rgb[k]!=rgb[i] and rgb[k]!=rgb[j]:
                    c-=1
print(c)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()

def main():
    n = int(input())
    S = list(input())
    R = set()
    G = set()
    B = set()

    def MIN(a, b):
        if a > b:
            return b
        else:
            return a
    def MAX(a, b):
        if a > b:
            return a
        else:
            return b

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

    b_len = len(B)
    ans = 0
    for r in R:
        for g in G:
            v1 = MIN(r, g)
            v2 = MAX(r, g)
            rg_diff = v2 - v1
            ans += b_len
            if v2 + rg_diff in B:
                ans -= 1
            if v1 - rg_diff in B:
                ans -= 1
            if (r + g) % 2 == 0 and (r + g) // 2 in B:
                ans -= 1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

c = 0

for i in range(N):
    x = 1
    while True:
        j = i + x
        k = j + x
        if k >= N:
            break
        if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
            c += 1
        x += 1

ans = S.count("R") * S.count("G") * S.count("B") - c
print(ans)

Submission status: Accepted

Solution code:
# ABC162d


def main():
    import sys
    sys.setrecursionlimit(10**6)
    # 再帰関数を使わない限りPypyで出すこと

    def dump(*args):
        sys.stderr.write(str(args))

    n = int(input())
    s = input()
    l = set(list('RGB'))
    cum = [[0]*(n+1) for _ in range(3)]
    for i in range(n):
        ind = -1
        if s[-i - 1] == 'R':
            ind = 0
        elif s[-i - 1] == 'G':
            ind = 1
        elif s[-i - 1] == 'B':
            ind = 2
        for j in range(3):
            cum[j][n - i-1] = cum[j][n - i]
        cum[ind][n - i-1] += 1
    ans = 0
    for i in range(n):
        for j in range(i + 1, n):
            if s[i] == s[j]:
                continue
            last = l.copy()
            last.discard(s[i])
            last.discard(s[j])
            ind = -1
            string = last.pop()
            if string == 'R':
                ind = 0
            elif string == 'G':
                ind = 1
            elif string == 'B':
                ind = 2
            ans += cum[ind][min(j+(j-i)+1, n)]+cum[ind][j+1] - \
                cum[ind][min(j+(j-i), n)]
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
n = int(input())
s = input()
d = defaultdict(int)
for c in s:
  d[c] += 1
ans = d['R'] * d['G'] * d['B']
for i in range(1, n):
  for j in range(n-2*i):
    if s[j] != s[j+i] and s[j+i] != s[j+2*i] and s[j+2*i] != s[j]:
      ans -= 1
print(ans)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    s = input()
    # まず第1の条件を満たす組をカウント
    ans = s.count('R') * s.count('G') * s.count('B')
    # その後、第2の条件も同時に満たす組を除外する
    for i in range(n - 2):
        for d in range(1, (n - i - 1) // 2 + 1):
            j, k = i + d, i + d * 2
            if s[i] != s[j] and s[i] != s[k] and s[j] != s[k]:
                ans -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
s = input()
count =[[0 for i in range(3)] for i in range(n+1)]
for i in range(1,n+1):
    if s[i-1] == 'R':
        count[i][0] = count[i-1][0] + 1
    else:
        count[i][0] = count[i-1][0]
    if s[i-1] == 'G':
        count[i][1] = count[i-1][1] + 1
    else:
        count[i][1] = count[i-1][1]
    if s[i-1] == 'B':
        count[i][2] = count[i-1][2] + 1
    else:
        count[i][2] = count[i-1][2]
ans = 0
words = set(['R','G','B'])
for i in range(n):
    for j in range(i+1,n):
        k = set([s[i],s[j]])
        if len(k) == 2:
            remain = (words - k)
            remain = list(remain)[0]
            d = j-i
            if remain == 'R':
                if j + d < n and s[j + d] == 'R':
                    ans += count[-1][0] - count[j][0] - 1
                else:
                    ans += count[-1][0] - count[j][0]
            elif remain == 'G':
                if j + d < n and s[j + d] == 'G':
                    ans += count[-1][1] - count[j][1] - 1
                else:
                    ans += count[-1][1] - count[j][1]
            else:
                if j + d < n and s[j + d] == 'B':
                    ans += count[-1][2] - count[j][2] - 1
                else:
                    ans += count[-1][2] - count[j][2]
print(ans)

Submission status: Accepted

Solution code:
def main():
    N = int( input())
    S = list( input())
    dp = [[0]*7 for _ in range(N)]
    if S[0] == "R":
        dp[0][0] = 1
    elif S[0] == "G":
        dp[0][1] = 1
    else:
        dp[0][2] = 1
    for i in range(1,N):
        s = S[i]
        for j in range(7):
            dp[i][j] = dp[i-1][j]
        if s == "R":
            dp[i][0] += 1
            dp[i][3] += dp[i-1][1]
            dp[i][5] += dp[i-1][2]
            dp[i][6] += dp[i-1][4]
        elif s == "G":
            dp[i][1] += 1
            dp[i][3] += dp[i-1][0]
            dp[i][4] += dp[i-1][2]
            dp[i][6] += dp[i-1][5]
        else:
            dp[i][2] += 1
            dp[i][4] += dp[i-1][1]
            dp[i][5] += dp[i-1][0]
            dp[i][6] += dp[i-1][3]
    # print(dp)
    ans = dp[N-1][6]
    # for i in range(N):
    #     ans += dp[i][6]
    # print(ans)
    for d in range(1,N//2+1):
        for i in range(N-d*2):
            # print(d,i,i+2*d)
            if S[i] != S[i+d] and S[i] != S[i+2*d] and S[i+d] != S[i+2*d]:
                ans -= 1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
S=input()
r,g,b=[0]*(N+1),[0]*(N+1),[0]*(N+1)
for x,c in ((r,'R'),(g,'G'),(b,'B')):
    for i in range(N):
        x[i+1]=x[i]+(1 if S[i]==c else 0)
a=0
for i in range(1,N-1):
    for j in range(i+1,N):
        for x,c in ((r,'R'),(g,'G'),(b,'B')):
            if S[i-1]!=S[j-1] and c not in (S[i-1],S[j-1]):
                a+=x[N]-x[j]-(x[2*j-i]-x[2*j-i-1] if 2*j-i<N+1 else 0)
print(a)

Submission status: Accepted

Solution code:


"""
NTC here
"""
import sys
inp = sys.stdin.readline
def input(): return inp().strip()
flush= sys.stdout.flush
# import threading
# sys.setrecursionlimit(10**6)
# threading.stack_size(2**26)

def iin(): return int(input())


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

# out = []
# range = xrange
# input = raw_input

def main():
    from bisect import bisect_right as br
    def find(a, b, c):
        sc = set(c)
        smc = len(c)
        ans = 0
        for i in a:
            for j in b:
                if j>i:
                    x = smc - br(c, j)
                    ans += x - (1 if (j-i)*2+i in sc else 0)
        return ans


    n = iin()
    s = input()
    dc = {'R':[], 'G':[], 'B':[]}
    for i in range(n):
        dc[s[i]].append(i)
    a, b, c = dc['R'], dc['B'], dc['G']
    ans = find(a, b, c) + find(a, c, b) + find(b, a, c) + find(b, c, a) + find(c, a, b) + find(c, b, a)
    print(ans)

main()
# threading.Thread(target=main).start()

Submission status: Accepted

Solution code:
n=int(input())
s=input()
raccum=[0]*n
gaccum=[0]*n
baccum=[0]*n
for i in range(n):
  if s[i]=='R':
    raccum[i]+=1
  if s[i]=='G':
    gaccum[i]+=1
  if s[i]=='B':
    baccum[i]+=1
for i in range(n-1):
  raccum[i+1]+=raccum[i]
  gaccum[i+1]+=gaccum[i]
  baccum[i+1]+=baccum[i]
ans=0
for i in range(n-2):
  for j in range(i+1,n-1):
    if s[i]=='R':
      if s[j]=='G':
        ans+=baccum[n-1]-baccum[j-1]
        if j+j-i<n and s[j+j-i]=='B':
          ans-=1
      if s[j]=='B':
        ans+=gaccum[n-1]-gaccum[j-1]
        if j+j-i<n and s[j+j-i]=='G':
          ans-=1
    if s[i]=='G':
      if s[j]=='R':
        ans+=baccum[n-1]-baccum[j-1]
        if j+j-i<n and s[j+j-i]=='B':
          ans-=1
      if s[j]=='B':
        ans+=raccum[n-1]-raccum[j-1]
        if j+j-i<n and s[j+j-i]=='R':
          ans-=1
    if s[i]=='B':
      if s[j]=='G':
        ans+=raccum[n-1]-raccum[j-1]
        if j+j-i<n and s[j+j-i]=='R':
          ans-=1
      if s[j]=='R':
        ans+=gaccum[n-1]-gaccum[j-1]
        if j+j-i<n and s[j+j-i]=='G':
          ans-=1
print(ans)

Submission status: Accepted

Solution code:
def main():
    n=int(input())
    s=list(input())
    ans=0
    how_r=[0 for i in range(n+1)]
    how_g=[0 for i in range(n+1)]
    how_b=[0 for i in range(n+1)]
    for i in range(n):
        string=s[i]
        if string=="R":
            how_r[i+1]+=1
        elif string=="G":
            how_g[i+1]+=1
        elif string=="B":
            how_b[i+1]+=1
    for i in range(n):
        how_r[i+1]+=how_r[i]
        how_g[i+1]+=how_g[i]
        how_b[i+1]+=how_b[i]


    for  i in range(n):
        for j in range(i+1,n):
            x=s[i]
            y=s[j]
            if x!=y:
                if "R" not in [x,y]:
                    ans+=how_r[j+1]-how_r[i]
                    if (i+j)%2==0:
                        if s[(i+j)//2]=="R":
                            ans-=1

                elif "G" not in [x,y]:
                    ans+=how_g[j+1]-how_g[i]
                    if (i+j)%2==0:
                        if s[(i+j)//2]=="G":
                            ans-=1

                elif "B" not in [x,y]:
                    ans+=how_b[j+1]-how_b[i]
                    if (i+j)%2==0:
                        if s[(i+j)//2]=="B":
                            ans-=1  
    print(ans)
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
from itertools import permutations
n = int(input())
s = input()
s_num = []

for i in range(n):
    num = 0
    if s[i] == 'G':
        num = 1
    elif s[i] == 'B':
        num = 2
    s_num.append(num)
# R: 0, G: 1, B: 2

# RGB, RBG, GBR, GRB, BRG, BGR

indexs = [[], [], []]
for i, v in enumerate(s_num):
    indexs[v].append(i)

color_sum = [[len(indexs[0])], [len(indexs[1])], [len(indexs[2])]]
for i in range(n):
    for j in range(3):
        if s_num[i] == j:
            color_sum[j].append(color_sum[j][-1] - 1)
        else:
            color_sum[j].append(color_sum[j][-1])

ans = 0
for i, j, k in permutations([0, 1, 2]):
    for first in indexs[i]:
        for second in indexs[j]:
            if second < first:
                continue
            third_exp = second + (second - first)
            if third_exp < n:
                if s_num[third_exp] == k:
                    ans -= 1
            tmp = color_sum[k][second]
            ans += tmp
#             print(tmp, ans)
# print(color_sum)
print(ans)

Submission status: Accepted

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

R = [0] * (N + 1)
G = [0] * (N + 1)
B = [0] * (N + 1)
for i, s in enumerate(S):
    R[i + 1] = R[i] + (s == 'R')
    G[i + 1] = G[i] + (s == 'G')
    B[i + 1] = B[i] + (s == 'B')
ans = 0
for i, s in enumerate(S):
    cnt1 = 0
    for j in range(i):
        if (i + i - j) >= N:
            continue
        t = S[j]
        u = S[i + (i - j)]
        if s != t and t != u and u != s:
            cnt1 += 1
    if s == 'R':
        X = G
        Y = B
    elif s == 'G':
        X = R
        Y = B
    else:
        X = R
        Y = G
    cnt2 = X[i] * (Y[N] - Y[i + 1])
    cnt3 = (X[N] - X[i + 1]) * Y[i]
    ans += (cnt2 + cnt3) - cnt1

print(ans)

Submission status: Accepted

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

order  = ["R", "G", "B"]
prefix = [[0 for i in range(n+1)] for i in range(3)]

for i in range(n):
	prefix[0][i+1] = prefix[0][i]
	prefix[1][i+1] = prefix[1][i]
	prefix[2][i+1] = prefix[2][i]
	if s[i] == "R":
		prefix[0][i+1] += 1
	elif s[i] == "G":
		prefix[1][i+1] += 1
	elif s[i] == "B":
		prefix[2][i+1] += 1
	else:
		print("Exception!")

# print("r_prefix", prefix[0])
# print("g_prefix", prefix[1])
# print("b_prefix", prefix[2])

ans = 0
for first in range(n):
	for second in range(first+1, n):
		if s[first] == s[second]:
			pass
		else:
			# print("first", first)
			# print("second", second)
			missing = list({"R", "G", "B"} - {s[first], s[second]})[0]
			mis_order = order.index(missing)

			# print("missing", missing)
			# print("mis_order", mis_order)
			to_exclude = second + (second - first)

			ans += prefix[mis_order][n] - prefix[mis_order][second+1]
			if to_exclude < n and s[to_exclude] == missing:
				ans -= 1
			# print("ans", ans)
			# print()
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s=input()
r=g=b=0
for index,value in enumerate(s):
    if value=="R":
        r+=1
    elif value=="G":
        g+=1
    else:
        b+=1
ans=r*g*b
for i in range((n-3)//2+1):
    for j in range(n-2-i*2):
        f1=s[j]
        f2=s[j+i+1]
        f3=s[j+2*i+2]
        if f1!=f2!=f3!=f1:
            ans-=1
print(ans)

Submission status: Accepted

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

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

RGB = [[0, 0, 0] for _ in range(N)]
S = S[::-1]
for i, s in enumerate(S):
    for j in range(3):
        RGB[i][j] = RGB[i - 1][j]
    RGB[i][rgb2num[s]] += 1
RGB = RGB[::-1]
S = S[::-1]
#print(RGB)
#print(S)

answer = 0
for m in range(1, N - 1):
    for l in range(m - 1, -1, -1):
        #print(m, l)
        if S[m] != S[l]:
            #print(S[m], S[l], m + 1, (3 - rgb2num[S[m]] - rgb2num[S[l]]))
            answer += RGB[m + 1][(3 - rgb2num[S[m]] - rgb2num[S[l]])]
            if 2 * m - l < N and S[2 * m - l] == num2rgb[3 - rgb2num[S[m]] - rgb2num[S[l]]]:
                answer -= 1
print(answer)

Submission status: Accepted

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

lr=set([])
lg=set([])
lb=set([])
for i in range(n):
    if s[i]=="R":
        lr.add(i)
    elif s[i]=="G":
        lg.add(i)
    else:
        lb.add(i)

m=0
for i in lr:
    for j in lg:
        if i+(i-j) in lb:
            m+=1
        if j-(i-j) in lb:
            m+=1
        if (i+j)/2 in lb:
            m+=1
print(len(lr)*len(lg)*len(lb)-m)

Submission status: Accepted

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

r_is = []
r_dic = {}
g_is = []
g_dic = {}
b_is = []
b_dic = {}

r_num = 0
g_num = 0
b_num = 0
for i, c in enumerate(s):
    if c=="R":
        r_is.append(i)
        #r_dic[i] = None
        r_num += 1
    elif c == "G":
        g_is.append(i)
        #g_dic[i] = None
        g_num += 1
    else:
        #b_is.append(i)
        b_dic[i] = None
        b_num += 1

out = 0
for ri in r_is:
    for gi in g_is:
        small_i = min(ri, gi) 
        big_i = max(ri, gi) 
        diff = big_i - small_i
        cur_b_num = b_num

        cand_i = small_i - diff
        if cand_i >= 0:
            try:
                b_dic[cand_i]
                cur_b_num -= 1
            except:
                pass

        cand_i = big_i + diff
        if cand_i <= n-1:
            try:
                b_dic[cand_i]
                cur_b_num -= 1
            except:
                pass

        # center
        wa = small_i + big_i
        if wa % 2 == 0:
            cand_i = wa // 2
            try:
                b_dic[cand_i]
                cur_b_num -= 1
            except:
                pass


        out += cur_b_num

print(out)

Submission status: Accepted

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

r = S.count('R')
g = S.count('G')
b = S.count('B')


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

print(r * g * b - counter)