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:
"""MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWO:,'..'xXWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMO. .:kOo.,kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMO. .lNWWo..lXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MNOxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxMMMMWKxoloxKWNc  .:xxd;  ,dxxxkXMXkxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxMM
MKc''''''''''''''''.  ..'''''.   .''''.  .''MMMWx..,:. .xXo''.  .''.  ..'';kMk;'''''.  .'.''.  .''''''.  ..''.   .''MM
MWNXNNNNNNNNNNNNNNNO' ;KNNNNNKo. cKNNNd. lXNMMMK; ,0Wx. :NWXXl .dNNO' ;KNNNWMWNNNNNXc .kNNNNx. cXNNNNNO' ;KNN0; 'ONNMM
MMMMMMMMMMMMMMMMMWM0' :NMMMMWMX: .OMWWx. oWMMMMWx. ';. .dNMWWo .xMM0' :NWWMMMMMMMMWWl .OMMMWk. lWWMMWM0' ;XMMX: ,KMMMM
MMMMMMWMWkccccccccc;. :NMWNNNKd. :XMMWx. oWMMMWKo. .',. .,ldx; .dMM0' :NMMMMMMMNNWMWl .OMMMWk. lWMMMMM0' ;XMMX: ,0MMMM
MMWXKNWMWxcc,. .;cc;. :XMk,''..'lKWMMWx. oWMNx:. .lONNKxl.     .xMM0' :NMMMMMM0:,oKO' ,KMMMMk. lWWNkoc,. .;::;. ,KMMMM
MMXc.lXMMWWWNd..xWM0' :NM0;  ;kXWMMMWNl  oWMK:.;xXWWMWXx:. ,c' .dMM0' :NMMMMMMKc. ...;kWMMMMk. lWWc .:;. .clc:. ,KMMMM
MWWx. lXMWMMMK, lWM0' :NMMNx'.,ldxxoc'   oWMWNKNWWWN0o' .:kNWo .dMM0' :NMMMMMMMNO;  ,OWWWMMMk. lWM' lXx. lNMMX: ,KMMMM
MMMWk'.,xKNX0c..kWM0' :NMMMMNkl;,'',:l:  oWMMMMMWMWO' 'l0WMWWo .xMM0' :NMMMMMMMMMNd. .oXWMMMk. lWMd.....;0WMMX: ,KMMMM
MMMMWKo'...'..:kWMM0' :NMMMMMMMWWNNWWWx. oWMMMMMMMMWOxXWMWMWWo .xMM0' :NMMMMMMMMMMMKl. ,kNMMk. lWMWKkxx0NMWMMX: ,KMMMM
MMMMMMMN0kxk0XNWMMWKl;xNMMMMMMMMMMMMWM0c;kWMMMMMMMMMMMWWMMMMWk;:OMMXl,dNMMMMMMMMMMMMWO; .dNM0c;kWWMMMMMMMMMMMNd,oXMMMM
MMMMMMMMWWMWMMMMMMMMMWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWMMWWMMWMMMMMMMMMMMMMMNkxKWMMWWMMMMMMMMMMMMMMWMMWMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM"""


#				 Author: Udit "luctivud" Gupta @ https://www.linkedin.com/in/udit-gupta-1b7863135/					 #


import math;   		from collections import *
import sys;   		from functools import reduce
import time;   		from itertools import groupby

# sys.setrecursionlimit(10**6)

def input()         : return sys.stdin.readline()
def get_ints()      : return map(int, input().strip().split())
def get_list()      : return list(get_ints())
def get_string()    : return list(input().strip().split())
def printxsp(*args) : return print(*args, end="")
def printsp(*args)  : return print(*args, end=" ")


DIRECTIONS = [(+0, +1), (+0, -1), (+1, +0), (+1, -1)] 
NEIGHBOURS = [(-1, -1), (-1, +0), (-1, +1), (+0, -1),\
              (+1, +1), (+1, +0), (+1, -1), (+0, +1)]



# MAIN >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

# for _test_ in range(int(input())): 
n, k = get_ints()
perm = [0] + get_list()
cost = [0] + get_list()
# ans = max(0, sum(cost) * ((k) // n))
# print(ans)
# k = (k % n) + 1

connected_comp = defaultdict(list)
visited = [False] * (n+1)
comps = 1
for i in range(1, n+1):
	on_square = i
	if not visited[on_square]:
		# visited[on_square] = True
		# print(i)
		while not visited[on_square]:
			visited[on_square] = True
			connected_comp[comps].append(on_square)
			on_square = perm[on_square]
		comps += 1
# print(connected_comp)
ans = 0
for key, val in connected_comp.items():
	x1 = len(val)
	ans1 = max(0, (sum(cost[i] for i in val)) * (k // x1))
	x2 = k % x1
	ans2 = 0
	for i in val:
		on_square = i
		this_ans = 0
		for j in range(x2):
			on_square = perm[on_square]
			this_ans += cost[on_square]
			ans2 = max(ans2, this_ans)
	ans = max(ans, ans1+ans2)
if ans < max(cost[1:]):
	print(max(cost[1:]))
else:
	print(ans)

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()))
was = [False]*n
sums = []
for i in range(n):
    if not was[i]:
        iWas = [False]*n
        pos = i
        sumn = [c[i]]
        while not iWas[pos]:
            iWas[pos] = True
            was[pos] = True
            pos = p[pos]-1
            sumn+=[c[pos]]
        sumn = sumn[:-1]
        sums.append(sumn)
m = -9999999999999999999999999
for i in range(len(sums)):
    totS = sum(sums[i])
    l = len(sums[i])
    for g in range(len(sums[i])):
        arr = []
        s = 0
        for j in range(l):
            s+=sums[i][(g+j)%l]
            arr.append(s)

        if totS > 1:
            m = max(m,totS*(k//l)+max(arr[:k%l]+[-99999999999999999999]))
        else:

            m = max(m, max(arr[:min(l,k)]))
print(m)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N,K=(int(x) for x in input().rstrip('\n').split())
Ps = [int(x)-1 for x in input().rstrip('\n').split()]
Cs = [int(x) for x in input().rstrip('\n').split()]
res = -10**9-1
for i in range(N):
  next = Ps[i]
  cycle = Cs[next]
  steps =[cycle]
  for a in range(1,K+1):
    next = Ps[next]
    cycle += Cs[next]
    steps.append(cycle)
    if next == i:
      if cycle>0:
        if K%(a+1)!=0:
          now = (K//(a+1))*cycle+max(steps[:K%(a+1)])
          if now>res:
            res = now
          break
        else:
          now =(K//(a+1))*cycle
          if now>res:
            res = now
          break
      else:
        now = max(steps)
        if now>res:
          res = now
        break
    if a==K:
      now = max(steps)
      if now>res:
        res = now
print(res)

Submission status: Wrong Answer

Solution code:
import numpy as np

N,K = map(int, input().split())
P = np.array(list(map(int, input().split())))
P = P - 1
C = np.array(list(map(int, input().split())))

max_score = 0
loc = np.arange(N)
score = np.zeros(N)
for i in range(K):
    loc = np.array([P[(loc[i])] for i in range(N)])
    score = score + np.array([(C[(loc[i])]) for i in range(N)])
    if max(score) > max_score:
        max_score = max(score)
        
print(int(max_score))

Submission status: Wrong Answer

Solution code:
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict as dd

def maxSumSubSizek(arr, k): 
    n = len(arr)
    res = 0
    for i in range(k): 
        res += arr[i] 

    curr_sum = res 
    for i in range(k, n): 
        curr_sum += arr[i] - arr[i-k] 
        res = max(res, curr_sum) 
    return res 

def main():
    n,k = map(int, input().split())
    perm = [0] + list(map(int, input().split()))
    sqscore = [0] + list(map(int, input().split()))


    ans = -10**10
    visited = [False]*(n + 1)
    for i in range(1, n + 1):
        if not visited[i]:
            cycleScores = []
            j = i
            cycsum = 0
            maxsum = -10**10
            while not visited[j]:
                visited[j] = True
                score = sqscore[j]
                cycsum += score
                maxsum = max(maxsum, score)
                cycleScores.append(sqscore[j])
                j = perm[j]
            
            if maxsum <= 0:
                # All numbers are negative/0; take one step.
                ans = max(ans, maxsum)
            else:
                # positive numbers exist in cycle
                if k > len(cycleScores):
                    if cycsum <= 0:
                        temp = cycleScores + cycleScores
                        msf = cycleScores[0]
                        for i in temp[1:]:
                            msf = max(msf + i, i)
                            ans = max(ans, msf)
                    else:
                        # finish k/len(cycScores) cycles. Whatever is left, find subarray with max sum of that length
                        mult = k // len(cycleScores)

                        tempans = mult * cycsum
                        k -= mult * len(cycleScores)
                        
                        # find subarray of size k with in cycleScore with max Sum.
                        temp = cycleScores + cycleScores
                        for step in range(1, k + 1):
                            ans = max(ans, tempans + maxSumSubSizek(temp, step))
                else:
                    temp = cycleScores + cycleScores
                    for step in range(1, k + 1):
                        ans = max(ans, maxSumSubSizek(temp, step))
    print(ans)


        




































# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
 
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
pl = list(map(int, input().split())) 
cl = list(map(int, input().split())) 

dp =[True]*n
resu = -10**10
for i in range(n):
    dp =[True]*n
    temp = i
    kari = 0
    kaisu = 0
    res = -10**10
    while dp[temp] and kaisu <= k:
        dp[temp] =False
        now = pl[temp]-1
        kari += cl[now] 
        temp = now
        kaisu +=1
        res = max(res,kari)
    if dp[temp]==False and kaisu<= k:
        if kari >=0:
            m = k // kaisu
            if k % kaisu ==0:
                m -=1
            resu = max(resu,res+kari*m)
    resu = max(resu,res)

print(resu)

Submission status: Wrong Answer

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

route = {}
point = {}

for idx, p in enumerate(P):
    route[idx+1] = p
    point[p] = C[p-1]

all_max = point[1]
for start in range(1, N+1):
    visit = set()
    visit.add(start)
    now_point = 0
    max_point = point[start]
    # print(start)
    for k in range(K):
        now_point += point[start]
        max_point = max(max_point, now_point)
        start = route[start]
        if start in visit:
            break
        visit.add(start)
    # print(k, now_point, start, K % k)
    if now_point > 0:
        now_point *= (K // (k+1))
        for k in range(K % (k+1)):
            now_point += point[start]
            max_point = max(max_point, now_point)
            start = route[start]
    # print(k, start, now_point)

    all_max = max(max_point, all_max)
print(all_max)

Submission status: Wrong Answer

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

n=0
loops=[]
loops_score=[]
searched=[False]*N
sum_len=0

for _ in range(N):
    n=searched.index(False)
    l=[]
    ls=[]
    for i in range(N):
        n=P[n]-1
        searched[n]=True
        if n in l:
            break
        l.append(n)
        ls.append(C[n])
    
    loops.append(l)
    loops_score.append(ls)
    sum_len+=len(l)
    if sum_len==N:
        break
    
#print(loops)
#print(loops_score)

ans=-1*float('inf')

for scores in loops_score:
    ans_=0
    ls=len(scores)
    scores_sum=sum(scores)
    
    if K>ls and scores_sum>0:
        ans_loop=scores_sum*(K//ls)
    else:
        ans_loop=0
        
    maxlen=min(K,ls)
    #print(maxlen)
    ex_scores=scores+scores[:-1]
    #print(ex_scores)
    le=ls*2-1
    
    ruiseki=[0]*(le+1)
    for i in range(1,le+1):
        ruiseki[i]=ruiseki[i-1]+ex_scores[i-1]
    #print(ruiseki)
    
    ans_=max(scores)
    
    if K>=2:
        for d in range(2,maxlen-1):
            #for j in range(le+1-d):
            for j in range(ls):
                ans_=max(ans_,ruiseki[j+d]-ruiseki[j])
                #print(scores[j:j+d])
                #print(le,d,j,ans_+ans_loop)
                if d==maxlen:
                    break
    ans=max(ans,ans_+ans_loop)
        
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


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]
    now = (K // cnt_loop[i]) * val
    ans = max(ans, now)
    r = K % cnt_loop[i]
    for j in range(r):
        now += points[i][j]
        ans = max(ans, now)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
input = sys.stdin.buffer.readline
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))
PG = {}
CG = {}
G = [-1] * (N + 1)


def f(n):
    if G[n] == -1:
        idx = len(PG) + 1
        _P = []
        _C = []
        i = n
        while True:
            if P[i] in _P:
                break
            _P.append(P[i])
            _C.append(C[P[i]])
            G[P[i]] = idx
            i = P[i]
        PG[idx] = _P
        CG[idx] = _C
    else:
        _P = PG[G[n]]
        _C = CG[G[n]]
        idx = _P.index(n) + 1
        # print(f'{idx=}')
        _P = _P[idx:] + _P[:idx]
        _C = _C[idx:] + _C[:idx]
    # print(f'{_P=}, {_C=}')
    if len(_P) < K:  # ぐるぐる回れる
        cumsum = np.array(_C).cumsum()
        if cumsum[-1] <= 0:  # cumsumの最後が0以下だったらぐるぐる回らずmaxのところでやめる
            ans = cumsum.max()
            # print(f'case 1 {cumsum=}, {ans=}')
            return ans
        div, mod = divmod(K, len(_P))
        if mod != 0:
            ans = div * cumsum[-1]
            ans = max(ans, ans + cumsum[:mod].max())
            return ans
        else:
            ans = (div - 1)* cumsum[-1]
            return ans
    else:
        cumsum = np.array(_C[:K]).cumsum()
        ans = cumsum.max()
        # print(f'{cumsum=}, {ans=}')
        return ans


# f(1)
# print('')
# f(2)
# print('')
# f(3)
# print('')
# f(4)
# print('')
# f(5)

ans = f(1)
for i in range(1, N + 1):
    ans = max(ans, f(i))
# print(f'last answer = {ans}')
# print(f'{G=}, {PG=}, {CG=}')
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools
N, K = map(int, input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
PC =[]
for i in range(N):
    PC.append([P[i], C[i]])
PC.sort()
Cs =[]
for i in range(N):
    Cs.append(PC[i][1])
if K%N == 0:
  Am = N
else: Am = K%N
MpAm = Cs[0]
for i in range(N):
    tmp = 0
    for j in range(1,Am):
        tmp = tmp + Cs[(i+j)%N]
        MpAm = max(MpAm, tmp)
ans = MpAm + max(0, sum(Cs)*(K//N))
if K//N > 0 and sum(Cs) > 0 and min(Cs)<0:
    ans += -min(Cs)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
p = [0] + p
c = list(map(int, input().split()))
c = [0] + c
score = [[0] * (n + 1) for _ in range(n + 1)]
l_cycle = [0] * (n + 1)
for i in range(1, n + 1):
    start = i
    move_cnt = 0
    nxt = i
    while move_cnt < n:
        nxt = p[nxt]
        score[i][move_cnt + 1] += score[i][move_cnt] + c[nxt]
        move_cnt += 1
        if nxt == start:
            l_cycle[start] = move_cnt
            break
# for i in range(1, n + 1):
#     print(score[i])
# print('l_cycle', l_cycle)
ans = -float('inf')
for s in range(1, n + 1):
    sk = k // l_cycle[s]
    # sk = (k - 1) // l_cycle[s]
    arieru = score[s][1:l_cycle[s] + 2]
    # print(s, arieru)
    # print(sk)
    temp = max(score[s][1:l_cycle[s] + 2])

    # print(f's={s}')
    # print(f'sk={sk}')
    # print('start:', s)
    # print('arieru', arieru)
    # print(temp, s)
    ans = max(ans, temp)
    if sk >= 2:
        temp += sk * score[s][l_cycle[s]]
        ans = max(ans, temp)
    # print('ans:', ans)
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = list(map(int,input().split()))
for i in range(n):
    p[i] -= 1
c = list(map(int,input().split()))

reach = [False]*n
x = []
for i in range(n):
    if reach[i]:continue
    buf = [c[i]]
    nexti = p[i]
    while nexti!=i:
        buf.append(c[nexti])
        reach[nexti] = True
        nexti = p[nexti]
    x.append(buf)

ans = max(c)
import itertools
for i in x:
    n = k//len(i)
    ind = k%len(i)
    ii = i+i
    r = list(itertools.accumulate(ii))
    a = max(0,r[len(i)-1]*n)
    b = 0
    buf = 0
    if n>1:
        for j in range(min(len(i),k+1)):
            buf += i[-(j+1)]
            b = max(b,buf)
    for j in range(len(i)):
        for k in range(1,min(len(i),k+1)):
            s = r[j+k]-r[j]
            if k<ind+1:
                ans = max(ans,a+s)
            ans = max(ans,b+s)
print(ans)

Submission status: Wrong Answer

Solution code:
import math

n,k = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
nex = 0
ans = 0
maxa = 0

if all(i < 0 for i in c):
    print(max(c))
    exit()

if n > k:
    for i in range(n):
        nex = i
        ans = 0

        for j in range(k):
            ans += c[p[nex]-1]
            if maxa < ans:
                maxa = ans
            nex = p[nex]-1
else:
    if sum(c) < 0:
        for i in range(n):
            nex = i
            ans = 0

            for j in range(n):
                ans += c[p[nex]-1]
                if maxa < ans:
                    maxa = ans
                nex = p[nex]-1
    else:
        maxa = max(c)
        for i in range(n):
            nex = i
            ans = sum(c)*math.floor(k/n)
            
            for j in range(k%n):
                ans += c[p[nex]-1]
                if maxa < ans:
                    maxa = ans
                nex = p[nex]-1        

print(maxa)

Submission status: Wrong Answer

Solution code:

def max2(x,y):
    return x if x > y else y

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

off = max(C)
m2 = off
for i in range(N):
    tmp = 0
    m1 = off
    l = i
    S = 0
    k = 0
    for j in range(N):
        S += C[l]
        l = P[l] - 1
        if l==i:
            k = j+1
            break
    cnt = K // k - (K % k == 0)
    a = K%k + (K % k == 0)*k
    l = i
    for j in range(a):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S > 0:
        m1 += cnt*S
    m2 = max2(m1, m2)

print(m2)
"""
4 10
2 3 4 1
1 2 3 4
"""

Submission status: Wrong Answer

Solution code:
import sys


def _ia(): return map(int, sys.stdin.readline().strip().split())


def calc(arr, k):
    s = sum(arr)
    n = len(arr)
    flag = s > 0 and k >= n

    kp = k % n if flag else k
    l = min(kp, n)

    cm = 0 if flag else max(arr)
    for i in range(n):
        cn = 0
        for ki in range(i, i+l):
            cn += arr[ki % n]
            cm = max(cn, cm)

    if flag:
        return s * (k//n) + cm
    else:
        return cm


def main():
    n, k = _ia()
    p = list(map(lambda x: x-1, _ia()))
    c = list(_ia())

    f = [False] * n
    g = []
    for idx in range(n):
        if f[idx]:
            continue

        nxt = idx
        tmp = [c[nxt]]
        f[nxt] = True

        for _ in range(n):
            nxt = p[nxt]
            if nxt == idx:
                break
            tmp.append(c[nxt])
            f[nxt] = True

        g.append(tmp)

    return max(calc(gi, k) for gi in g)


if __name__ == "__main__":
    print(main())

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = [int(i) for i in input().split()]
C = [int(i) for i in input().split()]
score_candidate = []
# 初期位置n
for n in range(N):
    flg = True
    # 現在の位置：cp(current position)
    cp = n
    # スコアの履歴
    score_history = []
    # 移動の履歴
    mv_history = []
    for k in range(K):
        # 次の位置 np(next position)
        np = P[cp]-1
        # スコア
        if len(score_history) == 0:
            score_history.append(C[np])
        else:
            score_history.append(score_history[-1] + C[np])
        mv_history.append(np)
        cp = np
        # ループしたかのチェック
        if mv_history[-1] in mv_history[:-1]:# ループした
            # 1loop 毎のスコアリスト
            score_1loop = score_history[mv_history[:-1].index(mv_history[-1]):-1]
            if sum(score_1loop) >= 0:
                # loop前のスコア
                init_score = sum(score_history[0:mv_history[:-1].index(mv_history[-1])])
                loop_cnt = K // len(score_1loop) - 1
                loop_score_sum = loop_cnt * sum(score_1loop)
                init_plus_loop_score = loop_score_sum + init_score
                last_K = K - len(score_history[0:mv_history[:-1].index(mv_history[-1])]) - loop_cnt * len(score_1loop)
                tmp = []
                for j in range(last_K):
                    if tmp == []:
                        tmp.append(init_plus_loop_score + score_1loop[0])
                    else:
                        if j >= len(score_1loop):
                            point = j - len(score_1loop)
                        else:
                            point = j
                        tmp.append(tmp[-1] + score_1loop[point])
            else:
                tmp = []
                for s in score_history:
                    if tmp == []:
                        tmp.append(s)
                    else:
                        tmp.append(tmp[-1] + s)
            flg = False
            break
    if flg:
        tmp = []
        for s in score_history:
            if tmp == []:
                tmp.append(s)
            else:
                tmp.append(tmp[-1] + s)
    score_candidate.append(max(tmp))
print(max(score_candidate))

Submission status: Wrong Answer

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

F=[0]*N
I=[0]*N
CN=[0]*N
if max(C)<0:
  print(max(C))
  exit()

for i in range(N):
  around=0
  cnt=0
  A=[]
  if F[i]==0:
    F[i]=1
    around+=1
    cnt+=C[i]
    nex=P[i]-1
    A.append(i)
    while F[nex]==0:
      A.append(nex)
      F[nex]=1
      around+=1
      cnt+=C[nex]
      nex=P[nex]-1
    for j in A:
      I[j]=around
      CN[j]=cnt
#print(F)
#print(I)
#print(CN)
ans=-(10**9)*2
for i in range(N):
  cnt=C[i]
  #動かす回数が一周に満たない時
  if (K+1)<=I[i]:
    d=0
    nex=i
    for j in range(K+1):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  #動かす回数が一周を超えるとき
  elif CN[i]<=0:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  else:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
    acnt=cnt
    bcnt=C[i]
    syuukai=(K+1)//I[i]
    nokori=(K+1)%I[i]
    syuukai-=1
    nokori+=I[i]
    d=0
    nex=i
    for j in range(nokori-1):
      d+=C[nex]
      nex=P[nex]-1
      bcnt=max(d,bcnt)
    bcnt+=syuukai*CN[i]
    cnt=max(acnt,bcnt,(syuukai+1)*CN[i])
  ans=max(ans,cnt)
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()))

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())

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i]-1)

ma = float('INF')*(-1)
listcase = []
cc=0
for i in uf.roots():
    st = uf.members(i)[0]
    listcase.append([])
    while True:
        listcase[cc].append(c[st])
        st=p[st]-1
        if st == uf.members(i)[0]:
            break
    cc+=1

for i in listcase:
    m = len(i)
    i*=k//m+2

    for l in range(m):
        dp=[0]*(m+k)
        dp[0]=max(i[l],0)
        for j in range(1,k):
            t=(j+l)%m
            dp[j]=max(dp[j-1]+i[t],0)
        ma = max(ma,max(dp))
print(ma)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
p = [i-1 for i in p]
c = list(map(int, input().split()))

minusOnly = True
for i in range(n):
    if c[i] > 0:
        minusOnly = False
        break

if minusOnly:
    print(max(c))
    exit()

ans = 0
used = [False]*n

for st in range(n):
    if not used[st]:
        gr = []
        now = st
        gr.append(st)
        used[st] = True
        while True:
            now = p[now]
            gr.append(now)
            used[now] = True
            if now == st:
                break
        gr.pop()

        cs = [c[i] for i in gr]
        s = sum(cs)
        point = 0
        r = k
        if k > len(gr):
            if s > 0:
                point += s*(k//len(gr))
                r -= len(gr)*(k//len(gr))
            else:
                r = len(gr)+1
        

        cs = cs + cs
        plus = 0
        for i in range(len(gr)):
            nowSum = 0
            for g in range(r):
                nowSum += cs[i+g]
                plus = max(plus, nowSum)
        
        point += plus
        ans = max(ans, point)

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

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

chk = [0]*N

loops_C = []

for i in range(N):
  
  if ( chk[i]==0 ):
    chk[i] = 1
    new_loop_C = [ C[i] ]
    next_node = P[i]-1
    
    while( chk[next_node] == 0 ):
      chk[next_node] = 1
      new_loop_C.append( C[next_node] )
      next_node = P[next_node]-1
    
    loops_C.append(new_loop_C)
    #print(chk,new_loop_C)

print(loops_C)