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:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

# mv_array = [set() for _ in range(n)]
score_mv_array = [[] for _ in range(n)]
score_array = [0]*n

def get_sum(array):
    score_array = [0]
    for i, a in enumerate(array):
        score_array.append(score_array[i]+a)
    return max(score_array)

def get_max(array, q, mod):
    if q == 0:
        m_score = get_sum(array[:mod])
    else:
        m_score = get_sum(array+array[:mod])
        m_score = sum(array)*(q-1) + m_score
    return m_score

for i in range(n):
    score = 0
    max_score = c[i]
    pos = i
    for j in range(k):
        pos = p[pos]-1
        # if pos in mv_array[i]:
        if pos == i:
            len_mv = len(score_mv_array[i])
            q, mod = divmod(k-j, len_mv)
            score += get_max(score_mv_array[i], q, mod)
            max_score = max(score, max_score)
            break
        score += c[pos]
        # mv_array[i].add(pos)
        score_mv_array[i].append(c[pos])
        max_score = max(score, max_score)
    score_array[i] = max_score

print(max(score_array))

Submission status: Wrong Answer

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

score_array = [0]*n

def get_sum(array):
    score_array = [0]
    for i, a in enumerate(array):
        score_array.append(score_array[i]+a)
    return max(score_array)

def get_max(array, q, mod):
    if q == 0:
        m_score = get_sum(array[:mod])
    else:
        m_score = get_sum(array+array[:mod])
        m_score = sum(array)*(q-1) + m_score
    return m_score


for i in range(n):
    score = 0
    score_mv_array = []
    max_score = c[i]
    pos = i
    for j in range(k):
        pos = p[pos]-1
        if pos == i:
            len_mv = j+1
            q, mod = divmod(k-j, len_mv)
            score += get_max(score_mv_array, q, mod)
            max_score = max(score, max_score)
            break
        score += c[pos]
        score_mv_array.append(c[pos])
        max_score = max(score, max_score)
    score_array[i] = max_score

print(max(score_array))

Submission status: Wrong Answer

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

score_array = [0]*n

def get_sum(array):
    score_array = [0]
    for i, a in enumerate(array):
        score_array.append(score_array[i]+a)
    return max(score_array)

def get_max(array, q, mod):
    if q == 0:
        m_score = get_sum(array[:mod])
    else:
        m_score = get_sum(array+array[:mod])
        m_score = sum(array)*(q-1) + m_score
    return m_score

max_score = -float('inf')

for i in range(n):
    score = 0
    score_mv_array = []
    pos = i
    for j in range(k):
        pos = p[pos]-1
        if pos == i:
            len_mv = j+1
            q, mod = divmod(k-j, len_mv)
            score += get_max(score_mv_array, q, mod)
            max_score = max(score, max_score)
            break
        score += c[pos]
        score_mv_array.append(c[pos])
        max_score = max(score, max_score)
    score_array[i] = max_score

print(max(score_array))

Submission status: Wrong Answer

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


def get_sum(array):
    score_array = [0]
    for i, a in enumerate(array):
        score_array.append(score_array[i]+a)
    return max(score_array)

def get_max(array, q, mod):
    if q == 0:
        m_score = get_sum(array[:mod])
    else:
        m_score = get_sum(array+array[:mod])
        m_score = sum(array)*(q-1) + m_score
    return m_score

max_score = -float('inf')

for i in range(n):
    score = 0
    score_mv_array = []
    pos = i
    for j in range(k):
        pos = p[pos]-1
        if pos == i:
            len_mv = j+1
            q, mod = divmod(k-j, len_mv)
            score += get_max(score_mv_array, q, mod)
            max_score = max(score, max_score)
            break
        score += c[pos]
        score_mv_array.append(c[pos])
        max_score = max(score, max_score)

print(max_score)

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul
from numba import njit, b1, i4, i8, f8

sys.setrecursionlimit(10**7)

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**9
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

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)

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    # INF = 1 << 60
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                next = P[next]

        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        # al = np.array([],dtype='int')
        if K < len(visited):
            for j in range(len(visited)-1):
                # al = np.append(al,C[visited[j+1]])
                al[j]=C[visited[j+1]]
            # print(al)
            # a_cum = np.array([],dtype='int')
            a_cum = np.zeros(len(al))
            a_cum = al.cumsum()
            a = a_cum.max()
            # print(a)
            # a = acum.max()
        else:        
            for j in range(len(visited)-1):
                # al = np.append(al,C[visited[j+1]])
                al[j]=C[visited[j+1]]
            visitedLoop = visited[loopStart:]
            # print("visitedLoop: ",visitedLoop)
            sum_visitedLoop = 0
            for j in range(len(visitedLoop)):
                sum_visitedLoop += C[visitedLoop[j]]
            if sum_visitedLoop<=0:
                # print(al)
                a = al.cumsum().max()
            else:
                # 残り回数を循環配列の長さで割った余り
                q,mod = divmod((K-len(visited)+1),len(visitedLoop))
                # print('q,mod:',q,mod)
                # am = np.array([0],dtype='int')
                am = np.zeros(mod+1)

                for j in range(1,mod+1):
                    # am = np.append(am,C[visitedLoop[j]])
                    am[j] = C[visitedLoop[j-1]]
                am_sum = am.cumsum().max()
                # print('al:',al)
                # print(visitedLoop)
                # print(sum_visitedLoop)
                # print('am:',am)
                a = al.cumsum()[-1] + q*sum_visitedLoop + am_sum
        best_score = max(best_score, a)
    return best_score

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

Submission status: Wrong Answer

Solution code:
0

Submission status: Wrong Answer

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

has_visited = [False]*N
score_max = -float('inf')

for i in range(N):
    if has_visited[i]:
        continue
    
    loop_val = []

    j = i
    while True:
        loop_val.append(C[j])
        has_visited[j] = True
        j = P[j] - 1
        if loop_val[0] == C[j]:
            break

    loop_length = len(loop_val)

    sm = 0
    for p in range(loop_length):
        sm += loop_val[p]
    

    if sm >= 0 and loop_length <= K:
        rem = [0]*(loop_length**2*2)

        for k in range(loop_length):
            rem[k*2*loop_length] = loop_val[k % loop_length]
            for l in range(1, loop_length + K % loop_length):
                rem[k*2*loop_length+l] = loop_val[(k+l) % loop_length] + rem[k*2*loop_length+l-1]

        res = sm * (K // loop_length - 1) + max(rem)
    else:
        rem = [0]*(loop_length**2)

        for k in range(loop_length):
            rem[k*loop_length] = loop_val[k % loop_length]
            for l in range(1, K % loop_length):
                rem[k*loop_length+l] = loop_val[(k+l) % loop_length] + rem[k*loop_length+l-1]
        
        res = max(rem)

    if res == 0:
        res = max(loop_val)
    
    if score_max < res:
        score_max = res

print(score_max)

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
from collections import defaultdict as D
from functools import reduce
import numpy as np
import sys
import os
from operator import mul
from numba import njit, b1, i4, i8, f8

sys.setrecursionlimit(10**7)

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**9
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353    

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)

@njit((i8, i8[:], i8[:]), cache=True)
def solve(K,P,C):
    N = len(P)
    # INF = 1 << 60
    best_score = -INF
    for i in range(N):
        s = set([i])
        visited = [i]
        # visited,loopStart = rec(visited,P[i],s)
        next = P[i]
        while True:
            if next in s:
                loopStart = visited.index(next)
                break
            else:
                s.add(next)
                visited.append(next)
                next = P[next]

        # print(visited,loopStart)
        al = np.zeros(len(visited)-1)
        # al = np.array([],dtype='int')
        if K < len(visited):
            for j in range(len(visited)-1):
                # al = np.append(al,C[visited[j+1]])
                al[j]=C[visited[j+1]]
            # print(al)
            # a_cum = np.array([],dtype='int')
            a_cum = np.zeros(len(al))
            a_cum = al.cumsum()
            a = a_cum.max()
            # print(a)
            # a = acum.max()
        else:        
            for j in range(len(visited)-1):
                # al = np.append(al,C[visited[j+1]])
                al[j]=C[visited[j+1]]
            visitedLoop = visited[loopStart:]
            # print("visitedLoop: ",visitedLoop)
            sum_visitedLoop = 0
            for j in range(len(visitedLoop)):
                sum_visitedLoop += C[visitedLoop[j]]
            if sum_visitedLoop<=0:
                # print(al)
                a = al.cumsum().max()
            else:
                # 残り回数を循環配列の長さで割った余り
                q,mod = divmod((K-len(visited)+1),len(visitedLoop))
                # print('q,mod:',q,mod)
                # am = np.array([0],dtype='int')
                am = np.zeros(mod+1)

                for j in range(1,mod+1):
                    # am = np.append(am,C[visitedLoop[j]])
                    am[j] = C[visitedLoop[j-1]]
                am_sum = am.cumsum().max()
                # print('al:',al)
                # print(visitedLoop)
                # print(sum_visitedLoop)
                # print('am:',am)
                a = al.cumsum()[-1] + q*sum_visitedLoop + am_sum
        best_score = max(best_score, a)
    return best_score

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

Submission status: Wrong Answer

Solution code:
def main():
    N, K = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))
    P = [p-1 for p in P]
    
    check = [False] * N
    ans = -float("inf")
    for i in range(N):
        if check[i]:
            continue
        start = i
        position = i
        score_list = []
        j = 0
        while True:
            check[position] = True
            if j == 0:
                score_list.append(C[P[position]])
                position = P[position]
            else:
                score_list.append(C[P[position]] + score_list[-1])
                position = P[position]
                if position == start:
                    # print(position, start)
                    break
            j += 1
            # print(check)
        # print("score_list", score_list)
        for j in range(len(score_list)):
            if j != 0:
                tmp = score_list.pop(0)
                score_list = [x-tmp for x in score_list]
                score_list.append(tmp + score_list[-1])
            # print(score_list)
            # 最大得点を求める
            base_score = 0
            # 何周もするとき、正なら多く周回したほうが値は大きくなる
            tmp_K = K
            if K > len(score_list) and score_list[-1] >= 0:
                base_score = score_list[-1] * (K // len(score_list))
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            elif K > len(score_list) and score_list[-1] < 0:
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            # print(score_list)
            if tmp_K == 0:
                tmp_max_score = base_score - sum(score_list) + max(score_list)
            elif base_score == 0 and max(score_list[:tmp_K]) < 0:
                tmp_max_score = max(score_list[:tmp_K])
            else:
                tmp_max_score = base_score + max(0, max(score_list[:tmp_K]))
                tmp_max_score = max(tmp_max_score,
                                    base_score - sum(score_list) + max(score_list))
            if tmp_max_score > ans:
                # print("tmp_max", tmp_max_score, tmp_K, score_list)
                ans = tmp_max_score
    print(ans)
            
    
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()))

if max(C) <= 0:
    ans = max(C)
else:
        
    # P に基づくパスの生成
    sz = 0
    dn = [False for i in range(N)]
    pths = []
    for edg in P:
        if not dn[edg-1]:        
            pth = [edg]
            x = P[edg-1]
            while x != edg:
                pth.append(x)
                dn[x-1] = True
                x = P[x-1]
            sz += len(pth)
            pths.append(pth)
        if sz == N: break
    
    # パス毎の最大値の比較
    mn = - 10 ** 9
    ans = mn
    for pth in pths:
        sm = 0
         
        # パスの総和
        al = 0
        for i in pth: al += C[i-1]
        if al > 0:
            sm += al * (K // len(pth))
            cnt = K % len(pth)
        else:
            cnt = len(pth)
        
        # パスの部分和
        pth2 = pth * 2
        mx = mn
        for i in range(len(pth)):
            fr = 0
            if fr > mx: mx = fr
            for j in range(cnt):  
                fr += C[pth2[j + i] - 1]
                if fr > mx: mx = fr
        sm += mx
        
        if sm > ans: ans = sm
        
print(ans)

Submission status: Wrong Answer

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

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

    def Unite(self,x,y):
        x=self.Find_Root(x)
        y=self.Find_Root(y)

        if x==y:return
        elif self.rank[x]>self.rank[y]:
            self.root[x] +=self.root[y]
            self.root[y]=x
        else:
            self.root[y] +=self.root[x]
            self.root[x]=y
            if self.rank[x]==self.rank[y]:
                self.rank[y] +=1

    def isSameGroup(self,x,y):
        return self.Find_Root(x)==self.Find_Root(y)

    def size(self,x):
        return -self.root[self.Find_Root(x)]

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

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

    def group_members(self):
        return {i:self.members(i) for i in self.roots()}

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


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

UnionFind=UnionFind(N+1)
for i in range(N):
    UnionFind.Unite(i+1,P[i])

D=UnionFind.group_members()
E=[]
for i in D:
    A,length=D[i],len(D[i])
    if A[0]==0:continue
    index,F=A[0]-1,[]
    while len(F)!=length:
        index=P[index]-1
        F.append(C[index])
    E.append(F)

ans=-float("inf")
for A in E:
    length=len(A)
    if sum(A)<0:
        A=A*2
        for i in range(length):
            point=0
            for j in range(min(K,length)):
                point +=A[i+j]
                ans=max(ans,point)
    else:
        div,mod=divmod(K,length)
        base=(div-1)*sum(A)
        ans=base
        A=A*3
        for i in range(length):
            point=0
            for j in range(mod+length):
                point +=A[i+j]
                ans=max(ans,base+point)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N, K = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))
    P = [p-1 for p in P]
    
    check = [False] * N
    ans = -float("inf")
    for i in range(N):
        if check[i]:
            continue
        start = i
        position = i
        score_list = []
        j = 0
        while True:
            check[position] = True
            if j == 0:
                score_list.append(C[P[position]])
                position = P[position]
            else:
                score_list.append(C[P[position]] + score_list[-1])
                position = P[position]
                if position == start:
                    # print(position, start)
                    break
            j += 1
            # print(check)
        # print("score_list", score_list)
        for j in range(len(score_list)):
            if j != 0:
                tmp = score_list.pop(0)
                score_list = [x-tmp for x in score_list]
                score_list.append(tmp + score_list[-1])
            # print(score_list)
            # 最大得点を求める
            base_score = 0
            # 何周もするとき、正なら多く周回したほうが値は大きくなる
            tmp_K = K
            if K > len(score_list) and score_list[-1] >= 0:
                base_score = score_list[-1] * (K // len(score_list))
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            elif K > len(score_list) and score_list[-1] < 0:
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            # print(score_list)
            if tmp_K == 0:
                tmp_max_score = base_score
            else:
                tmp_max_score = base_score + max(0, max(score_list[:tmp_K]))
            if tmp_max_score > ans:
                # print("tmp_max", tmp_max_score, tmp_K, score_list)
                ans = tmp_max_score
    print(ans)
            
    
main()

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict, deque
from copy import deepcopy
    
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]
def end_of_loop():raise StopIteration

def main():
    N, K = MI()
    P = LI()
    C = LI()
    #1週下再に加算されるスコア並びにあるますから出発した際に１マス進んだ際のスコアがわかればよい。
    #初期化
    ans = []
    result = -float('inf')
    #開始点
    for i in range(N):
        result2= 0
        # start
        temp = i
        d = [-float('inf')] * N
        for j in range(N):
            temp = P[temp]-1
            result2+=C[temp]
            d[j] = result2
            if temp == i:
                index = j+1
                score = result2
                if index < K:
                    amari = K % index
                    syou = K // index
                    if amari !=0:
                        result = max(result, syou*score, syou*score+max(d[0:amari]), max(d))
                    else:
                        result = max(result, syou*score, max(d))
                    break
                else:
                    result = max(result, max(d[0:K]))
                    break
    print(result)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    N, K = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))
    P = [p-1 for p in P]
    
    check = [False] * N
    ans = -float("inf")
    for i in range(N):
        if check[i]:
            continue
        start = i
        position = i
        score_list = []
        j = 0
        while True:
            check[position] = True
            if j == 0:
                score_list.append(C[P[position]])
                position = P[position]
            else:
                score_list.append(C[P[position]] + score_list[-1])
                position = P[position]
                if position == start:
                    # print(position, start)
                    break
            j += 1
            # print(check)
        # print("score_list", score_list)
        for j in range(len(score_list)):
            if j != 0:
                tmp = score_list.pop(0)
                score_list = [x-tmp for x in score_list]
                score_list.append(tmp + score_list[-1])
            # print(score_list)
            # 最大得点を求める
            base_score = 0
            # 何周もするとき、正なら多く周回したほうが値は大きくなる
            tmp_K = K
            if K > len(score_list) and score_list[-1] >= 0:
                base_score = score_list[-1] * (K // len(score_list))
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            elif K > len(score_list) and score_list[-1] < 0:
                tmp_K = K - (len(score_list) * (K // len(score_list)))
            # print(score_list)
            if tmp_K == 0:
                tmp_max_score = base_score
            else:
                tmp_max_score = base_score + max(score_list[:tmp_K])
            if tmp_max_score > ans:
                # print("tmp_max", tmp_max_score, tmp_K, score_list)
                ans = tmp_max_score
    print(ans)
            
    
main()

Submission status: Wrong Answer

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

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

    def Unite(self,x,y):
        x=self.Find_Root(x)
        y=self.Find_Root(y)

        if x==y:return
        elif self.rank[x]>self.rank[y]:
            self.root[x] +=self.root[y]
            self.root[y]=x
        else:
            self.root[y] +=self.root[x]
            self.root[x]=y
            if self.rank[x]==self.rank[y]:
                self.rank[y] +=1

    def isSameGroup(self,x,y):
        return self.Find_Root(x)==self.Find_Root(y)

    def size(self,x):
        return -self.root[self.Find_Root(x)]

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

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

    def group_members(self):
        return {i:self.members(i) for i in self.roots()}

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


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

UnionFind=UnionFind(N+1)
for i in range(N):
    UnionFind.Unite(i+1,P[i])

D=UnionFind.group_members()
E=[]
for i in D:
    A,length=D[i],len(D[i])
    if A[0]==0:continue
    index,F=A[0]-1,[]
    while len(F)!=length:
        index=P[index]-1
        F.append(C[index])
    E.append(F)

ans=-float("inf")
for A in E:
    length=len(A)
    if sum(A)<0:
        A=A*2
        for i in range(length):
            point=0
            for j in range(min(K,length)):
                point +=A[i+j]
                ans=max(ans,point)
    else:
        div,mod=divmod(K,length)
        base=div*sum(A)
        ans=base
        A=A*2
        for i in range(length):
            point=0
            for j in range(mod):
                point +=A[i+j]
                ans=max(ans,base+point)
print(ans)

Submission status: Wrong Answer

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

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

    def Unite(self,x,y):
        x=self.Find_Root(x)
        y=self.Find_Root(y)

        if x==y:return
        elif self.rank[x]>self.rank[y]:
            self.root[x] +=self.root[y]
            self.root[y]=x
        else:
            self.root[y] +=self.root[x]
            self.root[x]=y
            if self.rank[x]==self.rank[y]:
                self.rank[y] +=1

    def isSameGroup(self,x,y):
        return self.Find_Root(x)==self.Find_Root(y)

    def size(self,x):
        return -self.root[self.Find_Root(x)]

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

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

    def group_members(self):
        return {i:self.members(i) for i in self.roots()}

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


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

UnionFind=UnionFind(N+1)
for i in range(N):
    UnionFind.Unite(i+1,P[i])

D=UnionFind.group_members()
E=[]
for i in D:
    A,length=D[i],len(D[i])
    if A[0]==0:continue
    index,F=A[0]-1,[]
    while len(F)!=length:
        index=P[index]-1
        F.append(C[index])
    E.append(F)

ans=-float("inf")
for A in E:
    length=len(A)
    if sum(A)<0:
        A=A*2
        for i in range(length):
            point=0
            for j in range(min(K,length)):
                point +=A[i+j]
                ans=max(ans,point)
    else:
        div,mod=divmod(K,length)
        base=div*sum(A)
        A=A*2
        for i in range(length):
            point=0
            ans=max(ans,base)
            for j in range(mod):
                point +=A[i+j]
                ans=max(ans,base+point)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
loop_flags = [False] * N
loops = []
for i in range(N):
    if loop_flags[i]:
        continue
    next_cell = i
    loop = []
    while not loop_flags[next_cell]:
        loop_flags[next_cell] = True
        loop.append(C[next_cell])
        next_cell = P[next_cell] - 1
    if loop:
        loops.append(loop)
# print(loops)

ans = -float('inf')
for loop in loops:
    sum_score = sum(loop)
    if sum_score > 0:
        sum_val = sum_score * (K // len(loop))
        remain_K = K % len(loop)
    else:
        sum_val = 0
        remain_K = min(len(loop), K)
    if len(loop) == 1:
        target = sum_val
        ans = max(target, ans)
    else:
        for i in range(1, remain_K + 1):
            target = sum_val
            target += sum(loop[:i])
            ans = max(target, ans)
            for j in range(len(loop)):
                target = target - loop[j] + loop[(i + j) % len(loop)]
                ans = max(target, ans)
print(ans)