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(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))

S = []
for i in range(N):
    p, si = i, [0]
    ps = set()
    while P[p] not in ps:
        p = P[p]
        ps.add(p)
        si.append(si[-1] + C[p])
    si = si[1:]
    S.append(si)

ans = -float('inf')
for i in range(N):
    ans = max(ans, max(S[i]), S[i][-1] * (K // len(S[i])) + max(S[i][:(K % len(S[i]))] + [0]))

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()))
    vis = [0 for i in range(n)]
    grps = []
    g = 1
    for i in range(n):
        if vis[i] == 0:
            que = [i]
            vis[i] = g
            cnt = [i]
            while len(que)>0:
                st = que.pop(0)
                if vis[p[st]-1]!=0:
                    g += 1
                    grps.append(cnt)
                    break
                vis[p[st]-1] = g
                cnt.append(p[st]-1)
                que.append(p[st]-1)
    loop_sum = []
    for i in range(n):
        s = 0
        for j in range(len(grps[vis[i]-1])):
            s += c[grps[vis[i]-1][j]]
        loop_sum.append(s)

    ans = -1 * float('inf')
    for i in range(n):
        g_sum = []
        l_len = len(grps[vis[i]-1])
        loop = k//l_len
        lost = k - loop*l_len
        if lost == 0:
            lost = l_len
            loop -= 1
        s = 0
        point = i
        for _ in range(lost):
            point = p[point]-1
            s += c[point]
            g_sum.append(s)
        s += loop * loop_sum[i]
        if ans < max(s,max(g_sum)):
            ans = max(s,max(g_sum))
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

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
loops = []

for i in range(n):
    if check[i]:
        continue
    check[i] = True
    next = P[i]
    tmp = [i]
    while next != i:
        check[next] = True
        tmp.append(next)
        next = P[next]
    loops.append(tmp)

# print(loops)

ans = 0

for loop in loops:

    num = len(loop)
    sho = k // num
    r = k % num
    if r == 0:
        r = num
    L = [C[p] for p in loop]

    ans_tmp = 0

    ryaku = 0
    if sum(L) > 0:
        ryaku = sum(L) * sho

    L += L
    ACC = [0] + list(accumulate(L))
    for i in range(num):
        for j in range(1, r+1):
            ans_tmp = max(ans_tmp, ACC[i+j]-ACC[i]+ ryaku)

    ans = max(ans, ans_tmp)
if ans == 0:
    print(max(C))

print(ans)

Submission status: Wrong Answer

Solution code:
def roop(i,K):#ループを検出したい
    isroop=False
    last=[-1]*N
    lastcnt=[-1]*N
    n=i
    last[n]=0
    lastcnt[n]=0
    roopp=-1#ループ1回のポイント
    cnt=0
    rs=-1
    maxp=-10**30
    point=0
    while(True):
        cnt+=1
        n=P[n]
        point+=C[n]
        maxp=max(maxp,point)
        if last[n]!=-1:
            roopp=point-last[n]
            syuki=cnt-last[n]#ループ周期
            isroop=True
            rs=n
            start=last[n]
            break
        last[n]=point
        lastcnt[n]=cnt
        if cnt==K:
            break
    if not isroop:
        return  maxp
    K-=lastcnt[rs]
    allpoint=(K//syuki)*roopp
    K%=syuki
    j=0
    n=rs
    point=0
    maxpp=0
    while(j<K):
        j+=1
        n=P[n]
        point+=C[n]
        maxpp=max(maxpp,point)
    return max([start if rs!=i else C[P[i]],start+allpoint,start+allpoint+maxpp])
        
        
        

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

ans=-10**30
for i in range(N):
    r=roop(i,K)
    ans=max(ans,r)
print(ans)

Submission status: Wrong Answer

Solution code:
# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase

def main():
    n,k = map(int,input().split())
    p = list(map(int,input().split()))
    c = list(map(int,input().split()))
    ans = -10**20
    for i in range(1,n+1):
        cou = 1
        se = {i}
        ne = p[i-1]
        su = [c[ne-1]]
        maxi = c[ne-1]
        while ne not in se and cou < k:
            se.add(ne)
            ne = p[ne-1]
            su.append(su[-1]+c[ne-1])
            maxi = max(maxi,su[-1])
            cou += 1
        if su[-1] > 0 and cou<k:
            maxi = max(maxi,su[-1]*(k//len(su))+(0 if not k%len(su) else su[k%len(su)-1]))
        ans = max(ans,maxi)
    print(ans)

#Fast IO Region
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")

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()))
l = []
check = [True]*n
for i in range(1,n+1):
    if (check[i-1]==True):
        s = i
        sl = []
        tnp = i
        for j in range(n):
            tnp = p[tnp-1]
            check[tnp-1] = False
            sl.append(c[tnp-1])
            if (tnp==s):
                break
        l.append(sl)
#print(l)
ans = -float("inf")
for i in range(len(l)):
    if (len(l[i])<=k):
        if (sum(l[i])>0):
            x = k%len(l[i])
            tnp = -float("inf")
            for p in range(1,x+1):
                wa = sum(l[i][:p])
                tnp = max(tnp,wa)
                for j in range(len(l[i])):
                    wa -= l[i][j]
                    wa += l[i][(j+p)%len(l[i])]
                    tnp = max(tnp,wa)
            ans = max(ans, tnp + sum(l[i])*(k//len(l[i])) )
        else:
            tnp = -float("inf")
            for p in range(1,len(l[i])):
                wa = sum(l[i][:p])
                tnp = max(tnp,wa)
                for j in range(len(l[i])):
                    wa -= l[i][j]
                    wa += l[i][(j+p)%len(l[i])]
                    tnp = max(tnp,wa)
            ans = max(ans, tnp)
    tnp = -float("inf")
    for p in range(1,min(k,len(l[i]))+1):
        wa = sum(l[i][:p])
        tnp = max(tnp,wa)
        for j in range(len(l[i])):
            wa -= l[i][j]
            wa += l[i][(j+p)%len(l[i])]
            tnp = max(tnp,wa)
    ans = max(ans, tnp)
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()))


def compute_cycle_score(score_list):
    s = sum(score_list)
    N_ = len(score_list)
    if s > 0:
        L = K % N_
        M = K // N_
        score = M * s
    else:
        L = N_
        score = 0

    score_cand = []
    score_list_ = score_list + score_list
    #I = len(score_list)
    score_sum_k = score_list
    for k in range(1,L+1):
        if k > 1:
            score_sum_k = [ score_sum_k[i] + score_list_[i+k-1] for i in range(N_) ]
        s_ = max(score_sum_k)
        #score_sum_k, s_ = compute_scores_in_interval(score_list_, score_sum_k, I, k)
        score_cand.append(s_)
    if len(score_cand) > 0:
        score += max(score_cand)
    return score


Left = list(range(N))

scores_partition = []
while len(Left) > 0:
    temp = []
    start = min(Left)
    p = start
    init = True
    while p != start or init:
        init = False
        temp.append(C[p])
        Left.remove(p)
        p = P[p] - 1
    scores_partition.append(temp)


result = max(map(compute_cycle_score, scores_partition))
print(result)

Submission status: Wrong Answer

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

ans = -float('inf')
for i in range(N):
    s = 0
    j = i
    for k in range(K):
        j = P[j]-1
        s += C[j]
        ans = max(ans, s)
        if j==i: break
    rem = K - (k+1)
    if rem == 0: continue
    d,m = divmod(rem, k+1)
    s *= (d+1)
    for k in range(m):
        j = P[j]-1
        s += C[j]
        ans = max(ans, s)

print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from bisect import bisect_right

n,k=nii()
p=lnii()
c=lnii()

ans=0
for i in range(1,n+1):
  x=i
  seen=[i]
  t_ans=[0]
  t_max=0
  cnt=1
  while cnt<=k:
    next_x=p[x-1]
    t_max=max(t_max,c[next_x-1])
    t_ans.append(t_ans[-1]+c[next_x-1])
    cnt+=1

    inx=bisect_right(seen,next_x)
    if seen[inx-1]==next_x:
      break
    else:
      seen.append(next_x)

    x=next_x

  if cnt==k:
    ans=max(ans,t_max)
  else:
    ans=max(ans,t_max,t_ans[-1]*((k-cnt)//(cnt-inx)))

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()))
ans=-10**9
for st in range(N):
	now = st+1
	temp=[0]
	while(P[now-1] != st+1):
		temp.append(temp[-1]+C[P[now-1]-1])
		now = P[now-1]
	temp.append(temp[-1]+C[P[now-1]-1])
	if temp[-1]<=0:
		ans = max(ans, (max(temp[1:])))
	else:
		t=temp[-1]*(K//(len(temp)-1))
		t+=max(temp[:1+K%(len(temp)-1)])
		ans=max(ans, t)
		
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = list(map(int, input().split()))
P = {i:n-1 for i, n in enumerate(list(map(int, input().split())))}
C = {i:n for i, n in enumerate(list(map(int, input().split())))}

cand = []
for i in range(N):
    current = i
    max_val = [C[P[current]]]
    sum_val = C[P[current]]
    while P[current]!=i:
        current = P[current]
        sum_val += C[P[current]]
        if sum_val>max_val[-1]:
            max_val.append(sum_val)
        else:
            max_val.append(max_val[-1])
    if K<=len(max_val):
        cand.append(max_val[-1])
    else:
        if sum_val<=0:
            cand.append(max_val[-1])
        else:
            tmp_score = sum_val*(K//len(max_val))
            if K%len(max_val)>0:
                tmp_score += max_val[K%len(max_val)-1]
            cand.append(max(sum_val*(K//len(max_val)-1)+max_val[-1], tmp_score))
print(max(cand))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,K=map(int,input().split())
P=tuple(map(int1,input().split()))
C=tuple(map(int,input().split()))
loop=[[-INF,0] for _ in range(N)]
used=[False]*N
for v in range(N):
    stack=[]
    d=0
    cnt=0
    while True:
        if not used[P[v]]:
            v=P[v]
            stack.append(v)
            used[v]=True
            d+=C[v]
            cnt+=1
        else:
            for vv in stack:
                loop[vv][0]=d
                loop[vv][1]=cnt
            break
ans=-INF
for i in range(N):
    d=0
    v=i
    for cnt in range(1,K+1):
        v=P[v]
        if loop[v][0]==-INF:
            d+=C[v]
            ans=max(ans,d)
        else:
            break
    loopstart=v
    v=P[i]
    MAX=-INF
    dd=0
    for ccnt in range(1,K-cnt+1):
        loopn=(K-ccnt)//loop[loopstart][1]
        if v!=i:
            dd+=C[v]
            ans=max(ans,d+dd,d+dd+loopn*loop[loopstart][0])
            v=P[v]
        else:
            break
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
score = [0 for i in range(n)]
P = list(map(int,input().split()))
C = list(map(int,input().split()))
ans = -(10**100)
for i in range(n):
    start = i
    cur = i
    i_s_score = 0
    i_s_score_max = C[P[cur]-1]
    move_num = 0
    for j in range(n):
        cur = P[cur]-1
        i_s_score += C[cur]
        i_s_score_max = max(i_s_score, i_s_score_max)
        move_num += 1
        if cur == start:
            break
    if i_s_score <= 0:
        ans = max(ans, i_s_score_max)
    else:
        temp = i_s_score*(k//move_num)
        rest = k%move_num
        ans = max(ans, temp)
        i_s_score = temp
        for j in range(rest):
            cur = P[cur]-1
            i_s_score += C[cur]
            ans = max(ans, i_s_score)
print(ans)

Submission status: Wrong Answer

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

ans=-10**18

for i in range(N):
    cnt=K
    pos=i
    tmp=[0]
    base=C[pos]
    while cnt and P[pos]!=i:
        pos=P[pos]
        tmp.append(tmp[-1]+C[pos])
        base+=C[pos]
        cnt-=1
    if P[pos]==i:
        if base>0:
            test=base*(K//len(tmp))
            cnt=K%len(tmp)
            if cnt:
                ttt=max(tmp[j] for j in range(1,cnt+1))
                if test:
                    ttt=max(ttt,0)
                test+=ttt
            ans=max(ans,test)
        else:
            tmp.append(tmp[-1]+C[i])
            cnt=min(K,len(tmp)-1)
            if cnt:
                test=max(tmp[j] for j in range(1,cnt+1))
                ans=max(ans,test)
    else:
        test=max(tmp[j] for j in range(1,len(tmp)))
        ans=max(ans,test)


print(ans)

Submission status: Wrong Answer

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

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

dic_s={}
dic_i={}

for i in range(1,n+1):
    if not i in dic_i:
        dic_s[i]=0
        j=i
        while not j in dic_i:
            dic_i[j]=1
            j=p[j-1]
            dic_s[i]+=1
# print(dic_s)

ans=-float('inf')
for i in dic_s.keys():
    lst_p=[]
    lst_c=[]
    # print(i)
    for j in range(dic_s[i]):
        lst_p.append(p[i-1])
        i=p[i-1]
        lst_c.append(c[i-1])
    # print(lst_p)
    # print(lst_c)
    cnt=0
    sm=sum(lst_c)
    if sm>=0:
        cnt+=sm*(k//dic_s[i])
        lst=lst_c+lst_c
        cnt2=-float('inf')
        for j in range(dic_s[i]):
            tmp=0
            for l in range(k%dic_s[i]):
                tmp+=lst[j+l]
                cnt2=max(cnt2,tmp)
            # print(cnt2)
        ans=max(ans,cnt+cnt2)
    else:
        lst=lst_c+lst_c
        cnt2=-float('inf')
        for j in range(dic_s[i]):
            tmp=0
            for l in range(min(k,dic_s[i])):
                tmp+=lst[j+l]
                cnt2=max(cnt2,tmp)
            # print(cnt2)
        ans=max(ans,cnt+cnt2)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
from itertools import accumulate #list(accumulate(A))

N, K = mi()
P = li()
C = li()
ans = -float('inf')

for i in range(N):
    #score = 0
    ind = i
    his = []
    while True:
        ind = P[ind] - 1
        his.append(C[ind])
        if ind == i:
            #print(his)
            his = list(accumulate(his))
            L = len(his)
            if K > L:
                if his[-1] > 0:
                    if not K%L:
                        ans = max(ans, his[-1] * (K//L))
                    else:
                        ans = max(ans, max(his[:K%L]) + his[-1] * (K//L))
                else:
                    ans = max(ans, max(his))
            else:
                ans = max(ans, max(his))
            break

print(ans)

Submission status: Wrong Answer

Solution code:
(N, K) = [int(x) for x in input().split()]
P = [int(x) - 1 for x in input().split()]  # 0 indexed
C = [int(x) for x in input().split()]


inf = float("inf")


def getScore(K):
    best = [-inf for i in range(N)]
    pos = list(range(N))
    score = [0 for i in range(N)]
    for k in range(K):
        nextPos = [0 for i in range(N)]
        for j in range(N):
            nextPos[P[j]] = pos[j]
            score[pos[j]] += C[P[j]]
        pos = nextPos
        best = [max(best[i], score[i]) for i in range(N)]
    return best, score


cycleLen = 0
pos = list(range(N))
pos2 = [0 for i in range(N)]
while True:
    for i in range(N):
        pos2[P[i]] = pos[i]
    cycleLen += 1
    pos, pos2 = pos2, pos
    if pos == list(range(N)):
        break


if K <= cycleLen:
    best, score = getScore(K)
    print(max(best))
    exit()


numCycles, K = divmod(K, cycleLen)

if K == 0:
    numCycles -= 1
    K += cycleLen

best1, score1 = getScore(cycleLen)
best2, score2 = getScore(K)

ans = max(C)
for i in range(N):
    if score1[i] >= 0:
        ans = max(ans, score1[i] * numCycles + best2[i])
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()))
for i in range(N):
    P[i] -= 1

ans = -10**10
for i in range(N):
    T = []
    Check = [0]*N
    move = i
    count = 1
    while(True):
        if Check[move] != 0:
            break
        Check[move] = count
        T.append(C[P[move]])
        move = P[move]
        count += 1
    s = Check[move] - 1
    result_1 = -10**10
    total = 0
    for j in range(min(s, K)):
        total += T[j]
        result_1 = max(result_1, total)
    result_2 = -10**10
    total = 0
    for j in range(min(len(T), K)):
        total += T[j]
        result_2 = max(result_2, total)
    if K >= len(T):
        result_3 = 0
        result_3 += sum(T[:s])
        result_3 += sum(T[s:])*((K - len(T[:s])) // len(T[s:]))
        total = result_3
        for j in range((K - len(T[:s])) % len(T[s:])):
            total += T[j]
            result_3 = max(result_3, total)
    if K >= len(T):
        ans = max([result_1, result_2, result_3, ans])
    else:
        ans = max([result_1, result_2, ans])
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))
INF = 10**18
ans = -INF
for i in range(N):
    arr = []
    tot = 0
    rest = K
    visited = {}
    visited[i] = rest
    nex = i
    while rest:
        nex = P[nex]
        tot += C[nex]
        arr.append(tot)
        rest -= 1
        if nex in visited:
            loop = visited[nex]-rest
            #print("visited", loop, arr)
            if tot > 0:
                tot += (rest//loop)*tot
                rest = rest%loop
                while rest:
                    nex = P[nex]
                    tot += C[nex]
                    arr.append(tot)
                    rest -= 1
            break
        else:
            visited[nex] = rest
    #print(i, arr)
    ans = max(ans, max(arr))
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

cycles = []
cycleSums = []
visited = [False]*N
for i, p in enumerate(Ps):
    if visited[i]:
        continue
    cycle = []
    now = i
    S = 0
    while not visited[now]:
        visited[now] = True
        now = Ps[now] - 1
        cycle.append(Cs[now])
        S += Cs[now]
    cycles.append(cycle)
    cycleSums.append(S)

ans = float('-inf')
for cycle, cycleSum in zip(cycles, cycleSums):
    L = len(cycle)
    cycle = cycle + cycle
    DPL = ((K-1) % L + 1) + 1
    M = float('-inf')
    dp = [None]*DPL
    dp[0] = 0
    for c in cycle:
        ndp = [None]*DPL
        ndp[0] = 0
        for i in range(1, DPL):
            if dp[i-1] is None:
                break
            tmp = dp[i-1] + c
            ndp[i] = 0 if 0 > tmp else tmp
            M = M if M > tmp else tmp
        dp = ndp
    if cycleSum > 0:
        tmp = cycleSum * (K // L) + M
    else:
        tmp = M
    ans = ans if ans > tmp else tmp

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int,input().split())
def read_p(s):
    return int(s) - 1
p = list(map(read_p,input().split()))
c = list(map(int,input().split()))
ans = 0
for i in range(n):
    s = 0
    at = i
    for _ in range(k):
        at = p[at]
        s += c[at]
        ans = max(s, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
import collections
import bisect
import itertools

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

# https://note.nkmk.me/python-union-find/

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


def main():
    n, k = ns()
    p = na1()
    c = na()

    uf = UnionFind(n)
    for i, pi in enumerate(p):
        uf.union(i, pi)

    cycledist = [[0, 0] for _ in range(n)]
    for lis in uf.all_group_members().values():
        if cycledist[lis[0]][0] != 0:
            continue
        tmp = 0
        l = len(lis)
        for idx in lis:
            tmp += c[idx]
            cycledist[idx][1] = l
        for idx in lis:
            cycledist[idx][0] = tmp

    ans = -INF

    for i in range(n):
        tmp_ans = cycledist[i][0] * (k // cycledist[i][1])

        tmp = 0
        idx = i
        for _ in range(n):
            tmp += c[p[idx]]
            idx = p[idx]
            if _ < k % cycledist[i][1]:
                ans = max(ans, tmp, tmp + tmp_ans)
            else:
                ans = max(ans, tmp)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
*p, = map(int, input().split())
p = [v - 1 for v in p]
*c, = map(int, input().split())
minc = min(c)

ans = minc


def get_loop(i):
    pos = i
    cnt = 0
    cur_score = 0
    while cnt == 0 or pos != i:
        pos = p[pos]
        cur_score = cur_score + c[pos]
        cnt += 1
    return cnt, cur_score

# print(get_loop(2))

def solve(i, k):
    score = minc
    cur_score = 0
    pos = i
    loop_length, loop_score = get_loop(i)
    if k // loop_length > 0 and loop_score > 0:
        # print("%s: %s // %s, %s, %s" % (i, k, loop_length, cur_score, max_loop_score))
        cur_score = loop_score * (k // loop_length)
        score = max(cur_score, score)
        k %= loop_length
    else:
        k = min(k, loop_length)
    # print('rem k', k, "cur_score", cur_score)
    for _ in range(k):
        pos = p[pos]
        cur_score += c[pos]
        score = max(cur_score, score)
    # print("%s: %s" % (i, score))
    return score

for i in range(n):
    ans = max(ans, solve(i, k))
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = [int(x)-1 for x in input().split()]
c = list(map(int, input().split()))
realans = -1001001001
for i in range(n):
    count = 0
    now = i
    score = 0
    for _ in range(n):
        if now == i and count != 0:
            break
        now = p[now]
        count += 1
        score += c[now]
    ans = 0
    ans += score * (k // count)
    nk = k % count
    if ans < 0:
        if nk == 0:
            nk = 1
        ans = 0

    maxim = -1001001001
    now = i
    tmp = 0
    for j in range(nk):
        now = p[now]
        tmp += c[now]
        maxim = max(maxim, tmp)
    ans += maxim
    realans = max(realans, ans)
print(realans)

Submission status: Wrong Answer

Solution code:
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

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()))
const = sum(C)
max_val = -inf
for i in range(n):
  now = i
  point = 0
  max_point = -inf
  j = k
  while j >0:
    j-=1
    now = P[now]
    point += C[now]
    max_point = max(max_point,point)
    if now == i:
      if j == 0:break
      elif point > 0:
        point += point * ((j-1)//(k-j))
        if j % (k-j) != 0:j %= (k-j)
        else :j == (k-j)
      else:
        if j % (k-j) != 0:j %= (k-j)
        else :j == (k-j)
    max_point = max(max_point,point)
    # print(point)

  max_val = max(max_val,max_point)
  # print(max_point,i)
  # print(max_point)
  # print(max_point,point)
print(max_val)
# print(const,max_val,k)
# print(l*const)

Submission status: Wrong Answer

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

ans = -float('inf')
for i in range(N):
    s = 0
    j = i
    for k in range(K):
        j = P[j]-1
        s += C[j]
        ans = max(ans, s)
        if j==i: break
    if s < 0: continue
    rem = K - (k+1)
    if rem == 0: continue
    d,m = divmod(rem, k+1)
    s *= (d+1)
    for k in range(m):
        j = P[j]-1
        s += C[j]
        ans = max(ans, s)

print(ans)