Problem:


Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Wrong Answer

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
MOD = 10**9+7

N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

sumlist1 = [[0]*N for _ in range(N)]
walist = [[0]*N for _ in range(N)]
loopcount = [0]*N

for h in range(N):
    sumlist1[h][0] = C[h]
    walist[h][0] = C[h]
    now = h
    l = 0
    for i in range(1,N):
        now = P[now]-1

        if sumlist1[h][i-1] < 0:
            sumlist1[h][i] = C[now]
        else:
            sumlist1[h][i] += sumlist1[h][i-1] + C[now]
        walist[h][i] += walist[h][i-1] + C[now]
        
        l += 1
        if now == h:
            break
    else:
        l += 1
    loopcount[h] = l
#print(sumlist1)

maxlist = [0]*N
for i in range(N):
    T = loopcount[i]
    wa = walist[i][T-1]
    print(wa,T)

    loop = K//T
    amari = K%T

    if wa >= 0:
        if loop == 0:
            if amari != 0:
                maxlist[i] = wa*loop + max(sumlist1[i][:amari])
            else:
                maxlist[i] = max(sumlist1[i][:amari])
        else:
            if amari != 0:
                maxlist[i] = max(wa*loop + max(sumlist1[i][:amari]), wa*(loop-1) + max(sumlist1[i]))
            else:
                maxlist[i] = max(wa*loop, wa*(loop-1) + max(sumlist1[i][:T]))
            

    else:
        if loop == 0:
            maxlist[i] = max(sumlist1[i][:amari])
        else:
            maxlist[i] = max(sumlist1[i])

print(max(maxlist))
#print(sumlist1)

Submission status: Wrong Answer

Solution code:
from numba import jit
@jit
def execute():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))

    max_score = -10 ** 100

    for i in range(n):
        point, count = i+1, 0
        val = 0
        while (count < k):
          point = p[point-1]
          val += c[point - 1]
          if (count == 0):
            max_score = max(max_score, val)
          else:
            if (val <= 0):
              break
          count += 1

    print(max_score)

if __name__ == "__main__":
    execute()

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

N, K = map(int, input().split())
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))


ans = -INF
points = [[0] * 5005 for _ in range(N)]
cnt_loop = [0] * N
for i in range(N):
    nx = P[i]
    points[i][0] = C[nx]
    cnt = 1
    while i != nx:
        nx = P[nx]
        points[i][cnt] = points[i][cnt - 1] + C[nx]
        cnt += 1
    cnt_loop[i] = cnt

# for i in range(N):
#     print(points[i][:20])
# print(cnt_loop)

ans = -INF
for i in range(N):
    for j in range(min(K, 5005)):
        ans = max(ans, points[i][j])
    val = points[i][cnt_loop[i] - 1]
    if val >= 0:
        base = (K // cnt_loop[i]) * val
        ans = max(ans, base)
        r = K % cnt_loop[i]
        for j in range(r):
            now = base + points[i][j]
            ans = max(ans, now)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

N, K = map(int, input().split())
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))


ans = -INF
points = [[0] * 5005 for _ in range(N)]
cnt_loop = [0] * N
for i in range(N):
    nx = P[i]
    points[i][0] = C[nx]
    cnt = 1
    while i != nx:
        nx = P[nx]
        points[i][cnt] = points[i][cnt - 1] + C[nx]
        cnt += 1
    cnt_loop[i] = cnt

# for i in range(N):
#     print(points[i][:20])
# print(cnt_loop)

ans = -INF
for i in range(N):
    for j in range(min(K, 5005)):
        ans = max(ans, points[i][j])
    val = points[i][cnt_loop[i] - 1]
    base = (K // cnt_loop[i]) * val
    ans = max(ans, base)
    r = K % cnt_loop[i]
    for j in range(r):
        now = base + points[i][j]
        ans = max(ans, now)
print(ans)

Submission status: Wrong Answer

Solution code:
f=lambda:[*map(int,input().split())]
n,k=f()
p,c=f(),f()
p=[*map(lambda x:x-1,p)]
a=-1e9
for i in range(n):
  x=i
  l=[]
  s=0
  while 1:
    x=p[x]
    l+=[c[x]]
    s+=c[x]
    if x==i: break
  m=len(l)
  t=0
  for j in range(m):
    if j+1>k: break
    t+=l[j]
    a=max(a,t+(k-j-1)//m*s*(s>0))
print(a)

Submission status: Wrong Answer

Solution code:
n, k = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
import time

if n >= k:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        for j in range(k):
            now = p[now] - 1
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
        ans = max(max(score), ans)
else:
	time.sleep(10)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


class UnionFind:
    def __init__(self, n: int):
        self.n = n
        self.parents = [-1] * n
    
    def find(self, x: int):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    
    def union(self, x: int, y: int):
        x = self.find(x)
        y = self.find(y)
        
        if x == y:
            return
        if self.parents[y] < self.parents[x]:
            x, y = y, x
        
        self.parents[x] += self.parents[y]
        self.parents[y] = x
    
    def size(self, x: int):
        return -self.parents[self.find(x)]
    
    def same(self, x: int, y: int):
        return self.find(x) == self.find(y)
    
    def members(self, x: int):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
    
    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]
    
    def group_count(self):
        return len(self.roots())
    
    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}
    
    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


def solve():
    N, K = map(int, rl().split())
    P = list(map(lambda n: int(n) - 1, rl().split()))
    C = list(map(int, rl().split()))
    
    uf = UnionFind(N)
    for i in range(N):
        uf.union(i, P[i])
    roop_scores = defaultdict(int)
    for i in range(N):
        roop_scores[uf.find(i)] += C[i]
    
    ans = max(C)
    for s in range(N):
        roop_size = uf.size(s)
        roop_score = roop_scores[uf.find(s)]
        roop_cnt = K // roop_size
        if roop_cnt and 0 < roop_score:
            tmp = roop_score * (K // roop_size)
            rem = K % roop_size
            cur = s
            ans = max(ans, tmp)
            while rem:
                cur = P[cur]
                tmp += C[cur]
                ans = max(ans, tmp)
                rem -= 1
        cur = s
        tmp = 0
        cnt = min(roop_size, K)
        while cnt:
            cur = P[cur]
            tmp += C[cur]
            ans = max(ans, tmp)
            cnt -= 1
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split()) # 2 ≤ N ≤ 5000  ; 1 ≤ K ≤ 10^9
P = list(map(int,input().split()))
C = list(map(int,input().split())) # −10^9 ≤ C[i] ≤ 10^9

ring_P = []

def get_score(PP):
    max_score = K * -10**9
    #score = [0] * K
    score_sum = sum([C[i-1] for i in PP])
    
    for j in range(K%len(PP)):
        score_0 = 0
        for h in range(j+1):
            score_0 += C[PP[(h) % len(PP)]-1]
#        score[j] = score_sum
        max_score = max(max_score, score_0)
        for i in range(1,len(PP)):
            #score_0 = score[j]
            ind_1  = PP[(i+j) % len(PP)]
            ind_0  = PP[(i-1) % len(PP)]
            score_1p = C[PP[(i+j) % len(PP)]-1]
            score_1m = C[PP[(i-1) % len(PP)]-1]
            score_1 = score_0 + (C[PP[(i+j) % len(PP)]-1] - C[PP[(i-1) % len(PP)]-1])
            #score[j] = max(score_0, score_1)
            max_score = max(max_score, score_1)
            score_0 = score_1
    if score_sum > 0:
        max_score += score_sum * (K // len(PP))
    return max_score

max_score = K * -10**9
Arr = [0] * (N+1)
i = 1
while i < N+1:
    if Arr[i] != 1:
        ring_P.append([])
        PP = ring_P[-1]
        Arr[i] = 1
        init = i
        i = P[i-1]
        #print(i)
        PP.append(i)
        while init != i:
            Arr[i] = 1
            i = P[i-1]
            #print(i)
            PP.append(i)
        #print(PP)
        #print([C[i-1] for i in PP])
        #print(get_score(PP))
        max_score = max(get_score(PP),max_score)
    i += 1
#print(ring_P)
print(max_score)

Submission status: Wrong Answer

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
MOD = 10**9+7

N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

sumlist1 = [[0]*N for _ in range(N)]
walist = [[0]*N for _ in range(N)]
loopcount = [0]*N

for h in range(N):
    sumlist1[h][0] = C[h]
    walist[h][0] = C[h]
    now = h
    l = 0
    for i in range(1,N):
        now = P[now]-1

        if sumlist1[h][i-1] < 0:
            sumlist1[h][i] = C[now]
        else:
            sumlist1[h][i] += sumlist1[h][i-1] + C[now]
        walist[h][i] += walist[h][i-1] + C[now]
        
        l += 1
        if now == h:
            break
    else:
        l += 1
    loopcount[h] = l
#print(sumlist1)

maxlist = [0]*N
for i in range(N):
    T = loopcount[i]
    wa = walist[i][T-1]
    #print(wa)

    loop = K//T
    amari = K%T

    if wa >= 0:
        if loop == 0:
            if amari != 0:
                maxlist[i] = wa*loop + max(sumlist1[i][:amari])
            else:
                maxlist[i] = max(sumlist1[i][:amari])
        else:
            if amari != 0:
                maxlist[i] = max(wa*loop + max(sumlist1[i][:amari]), wa*(loop-1) + max(sumlist1[i]))
            else:
                maxlist[i] = max(wa*loop, wa*(loop-1) + max(sumlist1[i]))
            

    else:
        if loop == 0:
            maxlist[i] = max(sumlist1[i][:amari])
        else:
            maxlist[i] = max(sumlist1[i])

print(max(maxlist))
#print(sumlist1)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


class UnionFind:
    def __init__(self, n: int):
        self.n = n
        self.parents = [-1] * n
    
    def find(self, x: int):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    
    def union(self, x: int, y: int):
        x = self.find(x)
        y = self.find(y)
        
        if x == y:
            return
        if self.parents[y] < self.parents[x]:
            x, y = y, x
        
        self.parents[x] += self.parents[y]
        self.parents[y] = x
    
    def size(self, x: int):
        return -self.parents[self.find(x)]
    
    def same(self, x: int, y: int):
        return self.find(x) == self.find(y)
    
    def members(self, x: int):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
    
    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]
    
    def group_count(self):
        return len(self.roots())
    
    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}
    
    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


def solve():
    N, K = map(int, rl().split())
    P = list(map(lambda n: int(n) - 1, rl().split()))
    C = list(map(int, rl().split()))
    
    uf = UnionFind(N)
    for i in range(N):
        uf.union(i, P[i])
    roop_scores = defaultdict(int)
    for i in range(N):
        roop_scores[uf.find(i)] += C[i]
    
    ans = max(C)
    for s in range(N):
        roop_size = uf.size(s)
        roop_score = roop_scores[uf.find(s)]
        if 0 < roop_score:
            tmp = roop_score * (K // roop_size)
            rem = K % roop_size
            cur = s
            ans = max(ans, tmp)
            while rem:
                cur = P[cur]
                tmp += C[cur]
                ans = max(ans, tmp)
                rem -= 1
        cur = s
        tmp = 0
        cnt = min(roop_size, K)
        while cnt:
            cur = P[cur]
            tmp += C[cur]
            ans = max(ans, tmp)
            cnt -= 1
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    n, k = nm()
    P = nl()
    C = nl()
    visited = [0] * (n + 1)
    score = []

    for i in range(1, n + 1):
        if visited[i]:
            continue
        p = i
        tmp_s = []
        visited[p] = 1
        for j in range(n):
            p = P[p - 1]
            tmp_s.append(C[p - 1])
            if visited[p]:
                break
            visited[p] = 1

        score.append(tmp_s)

    ans = - float('Inf')

    for s in score:
        tmp = - float('Inf')
        le = len(s)
        if k > le:
            tmp_1 = - float('Inf')
            div, mod = divmod(k, le)
            for i in range(le):
                tmp_3 = 0
                for j in range(le):
                    p = i + j
                    if p >= le:
                        p -= le
                    tmp_3 += s[p]
                    tmp_1 = max(tmp_1, tmp_3)

            tmp_2 = 0
            tmp_2 += div * sum(s)
            s_r = s[-mod:] + s
            cum = np.cumsum(s_r)
            tmp_2 += max([cum[mod - 1]] + [cum[i + mod] - cum[i]
                                           for i in range(le)])
            tmp = max(tmp_1, tmp_2)

        else:
            for i in range(le):
                tmp_1 = 0
                for j in range(k):
                    p = i + j
                    if p >= le:
                        p -= le
                    tmp_1 += s[p]
                    tmp = max(tmp, tmp_1)

        ans = max(ans, tmp)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split()) 
P = list(map(int,input().split()))
C = list(map(int,input().split()))

num = []*(N-1)
print(num)

Submission status: Wrong Answer

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

[n,k] = [int(i) for i in input().split()]
p = [int(i)-1 for i in input().split()]
c = [int(i) for i in input().split()]

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i])
import collections
dic = collections.defaultdict(int)
for i in uf.roots():
    dic[i] = 0
ans = 0
total = collections.defaultdict(int)
for i in range(n):
    if dic[uf.find(i)] == 0:
        ls = uf.members(i)
        for j in ls:
            total[uf.find(i)] += c[j]
        dic[uf.find(i)] = 1
ans = - (10 ** 15)
for i in range(n):
    tmp = 0
    tmp_max = - (10 ** 15)
    members_len = len(uf.members(i))
    parent = uf.find(i)
    k_tmp = k
    #iからスタート
    if total[parent] >= 0:
        if k_tmp > members_len:
            tmp += total[parent] * (k_tmp // members_len)
            k_tmp -= members_len * (k_tmp // members_len)
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    else:
        k_tmp = members_len
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    ans = max(tmp_max,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = 10**18

N,K = LI()
P = LI()
C = LI()
C = np.array(C,dtype='int')
P = list(map(lambda x:x-1,P))
P = np.array(P,dtype='int')

# def rec(visited,next,s):
#     if next in s:
#         return visited,visited.index(next)
#     else:
#         s.add(next)
#         visited.append(next)
#         return rec(visited,P[next],s)
# テレポート, teleporter

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        # al = np.array([i])
        # al = np.delete(al,-1)
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                # al = np.append(al,C[next])
                next = P[next]
        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        # 残り回数を循環配列の長さで割った商と余り
        q,mod = divmod(K-len(visited)+1,len(visitedLoop))
        # print('q,mod:',q,mod)
        if q<1 or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            a = al_cum[-1] + (q-1)*am_cum[-1] + max(am_cum[-1]+am_cum[:mod+1].max(), am_cum.max())
            # a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
            # b = al_cum[-1] + (q-1)*am_cum[-1] + am_cum.max()
            # a = max(a,b)
            # else:
            #     a = al_cum[-1] + am_cum[:mod+1].max()
            #     b = al_cum.max()
            #     a = max(a,b)
        best_score = max(best_score, a)
    return best_score

res = solve(K,P,C)
print(int(res))

Submission status: Wrong Answer

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

[n,k] = [int(i) for i in input().split()]
p = [int(i)-1 for i in input().split()]
c = [int(i) for i in input().split()]

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i])
import collections
dic = collections.defaultdict(int)
for i in uf.roots():
    dic[i] = 0
ans = 0
total = collections.defaultdict(int)
for i in range(n):
    if dic[uf.find(i)] == 0:
        ls = uf.members(i)
        for j in ls:
            total[uf.find(i)] += c[j]
        dic[uf.find(i)] = 1
ans = - (10 ** 10)
for i in range(n):
    tmp = 0
    tmp_max = - (10 ** 10)
    members_len = len(uf.members(i))
    parent = uf.find(i)
    k_tmp = k
    #iからスタート
    if total[parent] >= 0:
        if k_tmp > members_len:
            tmp += total[parent] * (k_tmp // members_len)
            k_tmp -= members_len * (k_tmp // members_len)
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    else:
        k_tmp = members_len
        while k_tmp > 0:
            tmp += c[p[i]]
            i = p[i]
            tmp_max = max(tmp_max,tmp)
            k_tmp -= 1
    ans = max(tmp_max,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pos = [int(i) for i in input().split()]
score = [int(i) for i in input().split()]
if max(score) <= 0:
  print(max(score))
else:
  pos = [0] + pos
  score = [0] + score
  max_point = -10 ** 12
  dic = {}
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    if f_pos not in dic:
      point_loop = 0
      loop = 0
      pos_set = set([f_pos])
      while True:
        f_pos = pos[f_pos]
        point_loop += score[f_pos]
        #print('pos', f_pos)
        #print(point)
        loop += 1
        if f_pos in pos_set:
          for j in pos_set:
            dic[j] = [loop, point_loop]
          break
        pos_set.add(f_pos)
    else:
      loop, point_loop = dic[f_pos]
    #print(loop, point)
    loop_c = k // loop
    r = k % loop
    if point_loop > 0:
      point = loop_c * point_loop
      if point > max_point and loop_c > 0:
        max_point = point
    else:
      point = 0
      if loop_c > 0:
        r = loop
    #print(point)
    for _ in range(r):
      f_pos = pos[f_pos]
      point += score[f_pos]
      #print(point)
      if point > max_point:
        max_point = point
  #print('max_point')
  print(max_point)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
import os
from numba import njit, b1, i4, i8, f8

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = 10**18

N,K = LI()
P = LI()
C = LI()
C = np.array(C,dtype='int')
P = list(map(lambda x:x-1,P))
P = np.array(P,dtype='int')

# def rec(visited,next,s):
#     if next in s:
#         return visited,visited.index(next)
#     else:
#         s.add(next)
#         visited.append(next)
#         return rec(visited,P[next],s)
# テレポート, teleporter

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        # al = np.array([i])
        # al = np.delete(al,-1)
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                # al = np.append(al,C[next])
                next = P[next]
        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        for j in range(1,len(visited)):
                al[j-1]=C[visited[j]]
        al_cum = al.cumsum()        
        visitedLoop = visited[loopStart:]
        am = np.zeros(len(visitedLoop)+1)
        for j in range(len(visitedLoop)):
                am[j+1] = C[visitedLoop[j]]
        am_cum = am.cumsum()
        # ループ前 or ループがマイナスの場合
        # print('al: ',al)
        # print('am: ',am)
        q,mod = divmod(K-len(visited)+1,len(visitedLoop))
            # print('q,mod:',q,mod)
        if q==0 or am_cum[-1]<=0:
            a = al_cum.max()
        else:
            # 残り回数を循環配列の長さで割った商と余り
            
            # if q>0:
            a = al_cum[-1] + q*am_cum[-1] + am_cum[:mod+1].max()
            b = al_cum[-1] + (q-1)*am_cum[-1] + am_cum.max()
            a = max(a,b)
            # else:
            #     a = al_cum[-1] + am_cum[:mod+1].max()
            #     b = al_cum.max()
            #     a = max(a,b)
        best_score = max(best_score, a)
    return best_score

res = solve(K,P,C)
print(int(res))

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N, K = LI()
    P = LI_()
    C = LI()
    G = [-1 for _ in range(N)]
    for i, p in enumerate(P):
        G[i] = p
    seen = set()

    loop_score = []
    loop_size = []
    loop_id2node = collections.defaultdict(list)

    _id = 0
    def calc_one_loop(v):
        nodes = set()
        if G[v] == -1:
            return -1, -1
        # calc loop, and return score
        score = 0
        size = 0
        while G[v] not in seen:
            v = G[v]
            seen.add(v)
            nodes.add(v)
            score += C[v]
            size += 1
        return score, size, nodes

    for i in range(N):
        if i in seen:
            continue
        score, size, nodes = calc_one_loop(i)
        if score == -1 and size == -1:
            continue
        loop_score.append(score)
        loop_size.append(size)
        loop_id2node[_id].extend(list(nodes))
        seen.add(i)
        _id += 1

    # print(loop_score)
    # print(loop_size)
    # print(loop_id2node)
    ans = -inf
    for i in range(_id):
        # i: id
        n_loop = K // loop_size[i]
        # amari = min(K, loop_size[i])
        if loop_score[i] <= 0:
            max_step = min(K, loop_size[i])
            score = 0
        else:
            # 先に1周分少なく回る
            K -= max(n_loop-1, 0) * loop_size[i]
            score = max(n_loop-1, 0) * loop_score[i]
            max_step = K

        oneloop_max = -inf
        for l in range(1, max_step + 1):
            for v in loop_id2node[i]:
                cp_score = score
                cnt = 0
                while cnt < l:
                    v = G[v]
                    cnt += 1
                    cp_score += C[v]
                oneloop_max = max(oneloop_max, cp_score)
        ans = max(ans, oneloop_max)
    print(ans)



main()