Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

n=int(input())
s=input()
c=[[0,0,0] for _ in range(n+1)]
R=G=B=0
for j,i in enumerate(s):
    if i=="R":
        R+=1
    elif i=="G":
        G+=1
    else:B+=1
    c[j+1]=[R,G,B]
a=0
for i in range(1,n-1):
    for j in range(i):
        k=3-"RGB".index(s[i])-"RGB".index(s[j])
        if s[i]!=s[j]:
            a+=c[-1][k]-c[i][k]
            if 2*i-j<=n-1:
                if s[2*i-j]=="RGB"[k]:
                    a-=1
print(a)

### FIXED CODE ###

n=int(input())
s=input()
c=s.count
a=c("R")*c("G")*c("B")
for i in range(n-2):
    for j in range((n-i+1)//2):
        if s[i]!=s[i+j] and s[i+j]!=s[i+2*j] and s[i+2*j]!=s[i]:
            a-=1
print(a)
### BUGGY CODE ###

import numpy as np
def main():
    N = int(input())
    A = list(map(int, input().split()))
    Q = int(input())
    BC = [list(map(int, input().split())) for _ in range(Q)]

    Aset = set(A)
    
    others = Aset - set([b for b ,_ in BC]) - set([c for _ ,c in BC])

    Adict = dict()
    for a in A:
        Adict[a] = Adict.get(a, 0) + 1
    
    sum_others = 0
    for o in others:
        v = Adict.pop(o)
        sum_others += o*v
    
    for b, c in BC:
        if b in Adict:
            tmp = Adict[b]
            Adict[c] = Adict.get(c, 0) + tmp
            Adict.pop(b)
        
        goukei = sum([k*v for k, v in Adict.items()]) + sum_others
        
        print(goukei)


if __name__ == '__main__':
    main()


### FIXED CODE ###

def resolver(N, A, Q, BC):
    total = sum(A)
    counter = dict()
    ans = []
    for a in A:
        counter[a] = counter.get(a, 0) + 1
    
    for (b, c) in BC:
        c0 = counter.pop(b) if b in counter else 0
        counter[c] = counter.get(c, 0) + c0
        total -= c0 * b
        total += c0 * c
        ans.append(total)
    
    return ans

def test():
    pass

def main():

    #test()

    N = int(input())
    A = list(map(int, input().split()))
    Q = int(input())
    BC = []
    for _ in range(Q):
        bc = list(map(int, input().split()))
        BC.append(bc)

    ans = resolver(N, A, Q, BC)

    for a in ans:
        print(a)



if __name__ == '__main__':
    main()
### BUGGY CODE ###

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
  
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors
  
def isPrime(n):
  if n < 2:
    # 2未満は素数でない
    return False
  if n == 2:
    # 2は素数
    return True
  for p in range(2, n):
      if n % p == 0:
        # nまでの数で割り切れたら素数ではない
        return False
  # nまでの数で割り切れなかったら素数
  return True

A,B = list(map(int,input().split()))
 
aaa = []
 
aaa = make_divisors(gcd(A,B))
        
count = 0
 
for i in range(len(aaa)):
    if isPrime(aaa[i]) == True:
        count += 1
        
print(count+1)

### FIXED CODE ###

from fractions import gcd
 
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)
 
    # divisors.sort()
    return divisors
  
def isPrime(n):
  if n < 2:
    # 2未満は素数でない
    return False
  if n == 2:
    # 2は素数
    return True
  for p in range(2, int(n**0.5)+1):
      if n % p == 0:
        # nまでの数で割り切れたら素数ではない
        return False
  # nまでの数で割り切れなかったら素数
  return True
 
A,B = list(map(int,input().split()))
 
aaa = []
 
aaa = make_divisors(gcd(A,B))
        
count = 0
 
for i in range(len(aaa)):
    if isPrime(aaa[i]) == True:
        count += 1
        
print(count+1)
### BUGGY CODE ###

N, K = map(int, input().split())
T = [[0] * (2 * K + 5) for i in range(2 * K + 5)]
for i in range(N):
    x, y, c = input().split()
    x, y = int(x), int(y)
    if c == 'W':
        y += K
    T[x % (2 * K) + 1][y % (2 * K) + 1] += 1

for i in range(1, 2 * K + 1):
    for j in range(1, 2 * K + 1):
        T[i][j] += T[i][j - 1]


for j in range(1, 2 * K + 1):
    for i in range(1, 2 * K + 1):
        T[i][j] += T[i - 1][j]


num = 0
for i in range(K + 1):
    for j in range(K + 1):
        d = T[i][j]
        d += T[i + K][j + K] - T[i][j + K] - T[i + K][j] + T[i][j]
        d += T[2 * K][j] - T[i + K][j]
        d += T[i][2 * K] - T[i][j + K]
        d += T[2 * K][2 * K] - T[2 * K][j + K] - T[i + K][2 * K] + T[i + K][j + K]
        num = max(num, d)
        num = max(num, N - d)

print(num)


### FIXED CODE ###

N, K = map(int, input().split())
T = [[0] * (2 * K + 5) for i in range(2 * K + 5)]
for i in range(N):
    x, y, c = input().split()
    x, y = int(x), int(y)
    if c == 'W':
        y += K
    T[x % (2 * K) + 1][y % (2 * K) + 1] += 1

for i in range(1, 2 * K + 1):
    for j in range(1, 2 * K + 1):
        T[i][j] += T[i][j - 1]


for j in range(1, 2 * K + 1):
    for i in range(1, 2 * K + 1):
        T[i][j] += T[i - 1][j]


num = 0
for i in range(K + 1):
    for j in range(K + 1):
        d = T[i][j]
        d += T[i + K][j + K] - T[i][j + K] - T[i + K][j] + T[i][j]
        d += T[2 * K][j] - T[i + K][j]
        d += T[i][2 * K] - T[i][j + K]
        d += T[2 * K][2 * K] - T[2 * K][j + K] - T[i + K][2 * K] + T[i + K][j + K]
        num = max(num, d)
        num = max(num, N - d)

print(num)
### BUGGY CODE ###

#import heapq
import itertools
#import math
#import numpy as np
#import sys

N = int(input())
L = list(map(int, input().split()))
#S = [input() for _ in range(H)]
#T = [list(map(int,input().split())) for _ in range(N)]
#sys.exit()
L = sorted(L)
a = [(x, y, z) for (x, y, z) in itertools.combinations(L, 3) if ((x+y) > z) and ((x+z) > y) and ((y+z) > x)]
print(len(a))

### FIXED CODE ###

from bisect import bisect_left

N = int(input())
L = list(map(int, input().split()))

L.sort()
result = 0
for i in range(N - 2):
    for j in range(i + 1, N - 1):
        result += bisect_left(L, L[i] + L[j]) - j - 1
print(result)
### BUGGY CODE ###

n, k = map(int, input().split())
h = list(map(int, input().split()))
D = 1
if k != 0:
  while D <= k:
    if h == []:
      print(0)
      exit()
    else:
      h.remove(max(h))
      D += 1
sum1 = sum(h)
print(sum1)

### FIXED CODE ###

n, k = map(int, input().split())
h = list(map(int, input().split()))
h.sort()
h.reverse()
if k >= n:
    print(0)
else:
    del h[:k]
    print(sum(h))
### BUGGY CODE ###

N = int(input())
l = sorted(list(map(int, input().split())))

from bisect import bisect_left, bisect_right

cnt = 0
for i in range(N):
    a = l[i]
    for j in range(i, N):
        if i == j:
            continue
        b = l[j]
        l2 = l[:i] + l[i+1:j] + l[j+1:]
        start = bisect_right(l2, b-a)
        end = bisect_left(l2, a+b)
        cnt += len(l2[start:end])
print(cnt//3)

### FIXED CODE ###

N = int(input())
l = sorted(list(map(int, input().split())))
 
from bisect import bisect_left

cnt = 0
for i in range(N):
    a = l[i]
    for j in range(i+1, N):
        b = l[j]
        cnt += bisect_left(l[j+1:], a+b)
print(cnt)
### BUGGY CODE ###

def main():
    num = int(input())
    for i in range(num):
        X = " " + input()
        Y = " " + input()
        lx = len(X)
        ly = len(Y)
        max = 0
        XY = [[0] * ly for i in range(lx)]
        for j in range(1,lx):
            for k in range(1,ly):
                if X[j] == Y[k]:
                    XY[j][k] = XY[j-1][k-1] + 1
                elif XY[j-1][k] > XY[j][k-1]:
                    XY[j][k] = XY[j-1][k]
                else:
                    XY[j][k] = XY[j][k-1]
                if max < XY[j][k]:
                    max = XY[j][k]
        print(max)

if __name__ == '__main__':
    main()

### FIXED CODE ###

def main():
    num = int(input())
    A = []
    for i in range(num):
        X = input()
        Y = " " + input()
        lx = len(X)
        ly = len(Y)
        T = [0] * ly
        for j in range(lx):
            xj = X[j]
            C = T[:]
            for k in range(1,ly):
                k1 = k-1
                if xj == Y[k]:
                    T[k] = C[k1] + 1
                elif T[k] < T[k1]:
                    T[k] = T[k1]
        print(T[k])
if __name__ == '__main__':
    main()
### BUGGY CODE ###

import copy

N, K = map(int, input().split())
V = [int(i) for i in input().split()]

value = 0
# k+1個取って，ret-1個戻す
num = min(N*2,K)
for k in reversed(range(num)):
    for ret in range(num-k): #戻す個数はret個
        if (ret < k+1):
            #print('{}個取って{}戻す'.format(k+1,ret))
            for i in range(k+1+1): # 左右の分け方
                tmp = []
                V_tmp = copy.copy(V)
                #print('元々：',V_tmp)
                tmp.extend(V_tmp[:i]) # 左端
                #print('左端：',V_tmp[:i])
                V_tmp = V_tmp[i:]
                #print('左端取った：',V_tmp)
                if (k+1-i) > 0:
                    tmp.extend(V_tmp[-(k+1-i):]) #右端
                    #print('右端：',V_tmp[-(k+1-i):])
                # V_tmp = V_tmp[:-(k+1-i)]
                # print('右端取った：',V_tmp)
                if V_tmp == []:
                    break
                # ret個戻す
                tmp = list(filter(lambda x: x not in sorted(tmp)[:ret],tmp))
                #print('手元の宝石：',tmp)
                value = max(value,sum(tmp))
            #print()

print(value)

### FIXED CODE ###

import copy

N, K = map(int, input().split())
V = [int(i) for i in input().split()]

result = 0
# i個取る
for i in range(min(N,K)+1):
    #print('i:',i)
    for sp in range(i+1): # 左右の分け方
        #print('right',sp)
        #print('left',i-sp)
        tmp = []
        V_tmp = copy.copy(V)
        #print('元々：',V_tmp)
        tmp.extend(V_tmp[:sp]) # 左端追加
        #print('left',V_tmp[:sp])
        tmp.extend(V_tmp[N-(i-sp):]) #右端追加
        #print('right',V_tmp[N-(i-sp):])
        #print(tmp)
        tmp = sorted(tmp)
        value = sum(tmp)
        # ret個戻す
        for ret in range(0, min(K-i,i)): #残り操作回数か取った石の個数iの小さい方
            if ret < i:
                # マイナスの価値は戻す
                if tmp[ret] < 0:
                    value -= tmp[ret]
                    #print('捨てた宝石：',tmp[ret])
            else:
                break
        result = max(result,value)
            #print()

print(result)
### BUGGY CODE ###

import sys
import math
from collections import Counter
from collections import defaultdict

n = int(sys.stdin.readline())
a = ''.join(sys.stdin.readline().split())
c = Counter(a)
comb_num = defaultdict(int)
subtracted_comb_num = defaultdict(int)

def combinations_count(n, r):
    if n-r < 0: return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

for key in c.keys():
    comb_num[key] = combinations_count(int(c[key]), 2)
    subtracted_comb_num[key] = combinations_count(int(c[key])-1, 2)

total_comb_num = sum(comb_num.values())
for num in a:
    print(total_comb_num - comb_num[num] + subtracted_comb_num[num])


### FIXED CODE ###

import sys
import math
from collections import Counter

n = int(sys.stdin.readline())
a = sys.stdin.readline().split()
c = Counter(a)

total_comb_num = sum(map(lambda v: max(v*(v-1)//2, 0), c.values()))
for num in a:
    x = c[num]
    print(total_comb_num + max((x-1)*(x-2)//2, 0) - max((x*(x-1)//2, 0)))
### BUGGY CODE ###

n,k,q = [int(i) for i in str(input()).split(' ')]
a = [int(input()) for i in range(q)]

b = []
for i in range(n):
  b.append(k)

for i in range(q):
  for j in range(n):
    if a[i]-1 != j:
      b[j] = b[j] - 1

for i in range(n):
  if b[i] > 0:
    print("Yes")
  else:
    print("No")

### FIXED CODE ###

n,k,q = [int(i) for i in str(input()).split(' ')]
a = [int(input()) for i in range(q)]

b = [k - q] * n
for i in range(q):
  #b = list(map(lambda x: x - 1, b))
  b[a[i] - 1] += 1

for i in range(n):
  if b[i] > 0:
    print("Yes")
  else:
    print("No")
### BUGGY CODE ###

import sys
n = int(input())
arr = {}

for i in range(n):
    s = sys.stdin.readline().rstrip()
    if not s in arr:
        arr[s] = 1
    else:
        arr[s] += 1

dic = [key[0] for key in arr.items() if key[1] == max(arr.values())]
for i in sorted(dic):
    print(i)

### FIXED CODE ###

n = int(input())
arr = {}

for i in range(n):
    s = input()
    if not s in arr:
        arr[s] = 1
    else:
        arr[s] += 1

max_count = max(arr.values())
dic = [key[0] for key in arr.items() if key[1] == max_count]

out_sort = sorted(dic)
for i in out_sort:
    print(i)
### BUGGY CODE ###

def main():
    from collections import deque
    N, Q = (int(i) for i in input().split())
    G = [[] for _ in range(N)]
    cost = [0]*N
    for _ in range(N-1):
        a, b = (int(i) for i in input().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)
    G_color = ['WHITE' for _ in range(len(G))]
    G_distance = [float('inf') for _ in range(len(G))]
    G_parent = ['NIL' for _ in range(len(G))]

    def bfs(s):
        """
        breadth-first search
        -----
        G_color: BLACK if visited, GRAY if discovered, but will
             visit, WHITE if not discovered
        G_distance: a distance from s to v when algorithm computed
        G_parent: a predecessor of v. NIL if it not exist
        """
        G_color[s] = 'GRAY'
        G_distance[s] = 0
        Q = deque()
        Q.append(s)
        while Q:
            u = Q.popleft()
            for v in G[u]:
                if G_color[v] == 'WHITE':
                    G_color[v] = 'GRAY'
                    G_distance[v] = G_distance[u] + 1
                    G_parent[v] = u
                    Q.append(v)
            G_color[u] = 'BLACK'

    def dfs(v, x):
        seen = [False] * N
        todo = []
        seen[v] = True
        todo.append(v)
        while todo:
            u = todo[-1]
            for next_v in G[u]:
                if seen[next_v] or next_v == G_parent[u]:
                    continue
                seen[next_v] = True
                todo.append(next_v)
                break
            else:
                w = todo.pop()
                cost[w] += x

    bfs(0)
    for _ in range(Q):
        p, x = (int(i) for i in input().split())
        dfs(p-1, x)
    print(*cost)


if __name__ == '__main__':
    main()


### FIXED CODE ###

def main():
    import sys
    input = sys.stdin.buffer.readline
    from collections import deque
    N, Q = (int(i) for i in input().split())
    G = [[] for _ in range(N)]
    cost = [0]*N
    for _ in range(N-1):
        a, b = (int(i) for i in input().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)
    for _ in range(Q):
        p, x = (int(i) for i in input().split())
        cost[p-1] += x

    def bfs(s):
        G_color = ['WHITE' for _ in range(len(G))]
        G_color[s] = 'GRAY'
        Q = deque()
        Q.append(s)
        while Q:
            u = Q.popleft()
            for v in G[u]:
                if G_color[v] == 'WHITE':
                    G_color[v] = 'GRAY'
                    cost[v] += cost[u]
                    Q.append(v)
            G_color[u] = 'BLACK'

    bfs(0)
    print(*cost)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

N = int(input())
A = tuple(int(input()) for i in range(N))

B = list(A)

for j in range(N):
    B.pop(j)
    print(max(B))
    B = list(A)

### FIXED CODE ###

N = int(input())
A = list(int(input()) for i in range(N))

max_value = max(A)
number = A.count(max_value)

if number > 1:
    for j in range(N):
        print(max_value)
else:
    position = A.index(max_value)
    A.remove(max_value)
    for j in range(N):
        if j == position:
            print(max(A))
        else:
            print(max_value)
### BUGGY CODE ###


N = int(input())
A = list(map(int,input().split()))
#%%
bi = [[0]*20 for _ in range(N)]

state = [False]*20

for i,a in enumerate(A):
    tmp = a
    idx = 0
    while tmp>0:
        bi[i][idx] = tmp%2
        tmp >>= 1
        idx += 1

ans = 0
left = 0
right = 1

def upt(state,b):
    for i in range(20):
        if b[i]:
            state[i] = True
    return state
    
def rmv(state,b):
    for i in range(20):
        if b[i]:
            state[i] = False
    return state

def judge(state,b):
    for i in range(20):
        if state[i] and b[i]:
            return False
    return True

state = upt(state,bi[0])
#%%
while right<N:
    if judge(state,bi[right]):
        state = upt(state,bi[right])
        right += 1
    else:
        ans += right-left
        state = rmv(state,bi[left])
        left += 1

L = right - left
ans += L*(L+1)//2

print(ans)

### FIXED CODE ###


N = int(input())
A = list(map(int,input().split()))
#%%
bi = [[0]*20 for _ in range(N)]

state = [False]*20

for i,a in enumerate(A):
    tmp = a
    idx = 0
    while tmp>0:
        bi[i][idx] = tmp%2
        tmp >>= 1
        idx += 1

ans = 0
left = 0
right = 1

def upt(state,b):
    for i in range(20):
        if b[i]:
            state[i] = True
    return state
    
def rmv(state,b):
    for i in range(20):
        if b[i]:
            state[i] = False
    return state

def judge(state,b):
    for i in range(20):
        if state[i] and b[i]:
            return False
    return True

state = upt(state,bi[0])
#%%
while right<N:
    if judge(state,bi[right]):
        state = upt(state,bi[right])
        right += 1
    else:
        ans += right-left
        state = rmv(state,bi[left])
        left += 1

L = right - left
ans += L*(L+1)//2

print(ans)
### BUGGY CODE ###

N, M = map(int, input().split())
cards = sorted(list(map(int, input().split())))

for _ in range(M):
    B, C = map(int, input().split())
    for i in range(B):
        if cards[i] < C:
            cards[i] = C
        else:
            break
    cards.sort()

print(sum(cards))

### FIXED CODE ###

from collections import deque


N, M = map(int, input().split()) 
operation = [[1, card] for card in map(int, input().split())]

for _ in range(M):
    operation.append(list(map(int, input().split())))

operation.sort(key=lambda x:x[1], reverse=True)
operation = deque(operation)

maximum = 0
for _ in range(N):
    maximum += operation[0][1]
    operation[0][0] -= 1
    if operation[0][0] == 0:
        operation.popleft()

print(maximum)
### BUGGY CODE ###

N = int(input())
A = list(map(int, input().split(' ')))
num_sum = 0
for i in range(1, N+1):
    c = A.count(i)
    num_sum += int(c * (c - 1) / 2)

for j in A:
    if A.count(j) == 1:
        print(num_sum)
    else:
        print(num_sum - (A.count(j) - 1))

### FIXED CODE ###

'''
import numpy as np
N = int(input())
A = np.array(list(map(int, input().split(' '))))
num_sum = 0
remove_array = np.array([], int)
for i in range(N):
    c1 = np.count_nonzero(A == i + 1)
    c2 = np.count_nonzero(A == A[i])
    if c2 <= 1:
        remove_array = np.append(remove_array, 0)
    else:
        remove_array = np.append(remove_array, c2 - 1)
    num_sum += int(c1 * (c1 - 1) / 2)
print(*(num_sum - remove_array), sep='\n')
'''
import collections
N = int(input())
A = list(map(int, input().split()))
cnt = collections.Counter(A)
total = 0
for key in cnt.keys():
    total += cnt[key] * (cnt[key] - 1) // 2
for i in range(N):
    tmp = total
    tmp -= cnt[A[i]] * (cnt[A[i]] - 1) // 2
    tmp += (cnt[A[i]] - 1) * (cnt[A[i]] - 2) // 2
    print(tmp)
### BUGGY CODE ###

S = input()
Q = int(input())

r = False
for _ in range(Q):
    q = input().split()
    if q[0] == '1':
        r = not r
    else:
        if (q[1] == '1' and not r) or (q[1] == '2' and r):
            S = q[2] + S
        else:
            S = S + q[2]
            
if r:
    S = ''.join(reversed(S))
print(S)

### FIXED CODE ###

import sys
readline = sys.stdin.readline
read = sys.stdin.read

S = input()
Q = int(input())

u = ''
t = ''

r = False
for _ in range(Q):
    q = readline().split()
    if q[0] == '1':
        u, t = t, u
        r = not r
    else:
        if q[1] == '1':
            t += q[2]
        else:
            u += q[2]
            
if r:
    print(t[::-1]+S[::-1]+u)
else:
    print(t[::-1]+S+u)
### BUGGY CODE ###

import re
N, Q = input().split()
N = int(N)
Q = int(Q)
S=str(input())

for i in range(Q):
  l, r = input().split()
  l = int(l)
  r = int(r)
  s = S[l-1:r]

  AA = False
  cnt = 0
  for j in s:
    if AA:
      if j=="C": cnt += 1
      AA = False
    else:
      if j=="A": AA = True
  print(cnt)

### FIXED CODE ###

N, Q = input().split()
N = int(N)
Q = int(Q)
S=str(input())

im = [0 for i in range(N)]
AA = False
for i,v in enumerate(S):
  if AA:
    if v=="C": im[i] += 1
    elif v=="A": continue
    AA = False
  else:
    if v=="A": AA=True

for i in range(1,N):
  im[i] = im[i-1]+im[i]

for i in range(Q):
  l, r = input().split()
  l = int(l)-1
  r = int(r)-1
  print(im[r]-im[l])
### BUGGY CODE ###

n = int(input())
A = list(map(int, input().split()))

mod = 10 ** 9 + 7
ans = 0

for k in range(n):
    if A[k] > 500000000 :
        A[k] = A[k] - mod

for j in range(n):
    for i in range(j):
        tmp = A[i]*A[j] % mod
        ans = ans+tmp
ans = ans % mod
print(ans)

### FIXED CODE ###

n = int(input())
A = list(map(int, input().split()))

mod = 10 ** 9 + 7

summ = 0
quadsum = 0

for k in range(n):
    summ = (summ + A[k]) % mod
    quadsum = (quadsum + A[k]*A[k])%mod

ans = (summ*summ)%mod - quadsum
if ans % 2 == 1:
    ans += mod
ans = (ans/2)%mod
print(int(ans))
### BUGGY CODE ###

N = int(input())
A = list(input().split())
A = [int(i) for i in A]
ans = 1
for i in A:
    ans *= i
if ans > 10**18:
    print('-1')
else:
    print(ans)


### FIXED CODE ###

N = int(input())
A = list(input().split())
A = [int(i) for i in A]
if 0 in A:
    print(0)
    exit(0)

ans = 1
for i in A:
    ans *= i
    if ans > 10**18:
        print('-1')
        exit(0)
print(ans)
### BUGGY CODE ###

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
for k in range(N):
  P[k] -= 1
scorelist = []
roop = []
now = 0
visited = [-1 for _ in range(N)]
for k in range(N):
  now = k
  if visited[now] == -1:
    roop.append([])
    scorelist.append([])
    start = 0 + now
    while visited[start] == -1:
      roop[-1].append(start)
      visited[start] = 1 
      start = P[start]
      scorelist[-1].append(C[start])
    scorelist[-1] = scorelist[-1] + scorelist[-1]
    
#print(roop)
#print(scorelist)

ans = - float('inf')
for l in range(len(roop)):
  #print(scorelist[l][:len(roop[l])])
  Q = K // len(roop[l])
  R = K % len(roop[l])
  if Q > 0 and R == 0:
    Q -= 1
    R = len(roop[l]) 
  #print(Q, R)
  if sum(scorelist[l][:len(roop[l])]) > 0:
    basis = sum(scorelist[l][:len(roop[l])])*Q
  else:
    basis = 0
  #print(basis)
  adv = - float('inf')
  for k in range(len(roop[l])):
    for j in range(k, k + R):
      adv = max(adv, sum(scorelist[l][k:j+1]))
  ans = max(ans, basis + adv)

print(ans)

### FIXED CODE ###

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
for k in range(N):
  P[k] -= 1
scorelist = []
roop = []
now = 0
visited = [-1 for _ in range(N)]
for k in range(N):
  now = k
  if visited[now] == -1:
    roop.append([])
    scorelist.append([])
    start = 0 + now
    while visited[start] == -1:
      roop[-1].append(start)
      visited[start] = 1 
      start = P[start]
      scorelist[-1].append(C[start])
    scorelist[-1] = scorelist[-1] + scorelist[-1] + scorelist[-1]
    
#print(roop)
#print(scorelist)

ans = - float('inf')
for l in range(len(roop)):
  #print(scorelist[l][:len(roop[l])])
  Q = K // len(roop[l])
  R = K % len(roop[l])
  if Q > 0:
    Q -= 1
    R += len(roop[l]) 
  #print(Q, R)
  if sum(scorelist[l][:len(roop[l])]) > 0:
    basis = sum(scorelist[l][:len(roop[l])])*Q
  else:
    basis = 0
  #print(basis)
  advlist = -float('inf')
  for k in range(len(roop[l])):
    adv = 0
    for j in range(k, k + R):
      adv += scorelist[l][j]
      advlist  = max(advlist, adv) 
  ans = max(ans, basis + advlist)

print(ans)