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()))
INF = 10**18
ans = -INF
for i in range(N):
    arr = []
    tot = 0
    cnt = 0
    nex = i
    while cnt < K:
        nex = P[nex]
        tot += C[nex]
        arr.append(tot)
        cnt += 1
        if nex == i:
            break
    rest = K - cnt
    if rest:
        cycle = cnt
        cycle_score = tot
        if cycle_score > 0:
            tot += (rest//cycle)*cycle_score
            arr.append(tot)
            rest %= cycle
        while P[nex] != i and rest:
            nex = P[nex]
            tot += C[nex]
            arr.append(tot)
            rest -= 1
    ans = max(ans, max(arr))
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()))

#各地点からN回移動したときのスコアをあらかじめ求める
score = [[0 for j in range(N + 1)] for i in range(N)]
loop = [None for _ in range(N)]

for i in range(N):
    tmp = i
    flag = False
    for j in range(1, N + 1):
        tmp = P[tmp]
        score[i][j] = score[i][j - 1] + C[tmp]
        if tmp == i and not flag:
            loop[i] = j
            flag = True

if K <= N:
    res = -10**20
    for i in range(N):
        for j in range(1, K + 1):
            res = max(res, score[i][j])
    print(res)

else:
    res = -10**20
    for i in range(N):
        for j in range(1, N + 1):
            res = max(res, score[i][j])
    for i in range(N):
        tmp = 0
        if score[i][loop[i]] > 0:
            s = score[i][loop[i]] * (K // loop[i])
            res = max(res, s)
            for j in range(1, K % loop[i] + 1):
                tmp = score[i][j]
                res = max(res, s + tmp)
    print(res)

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=-float("inf")

for start in range(N):
    cur=P[start]
    scores=[C[cur]]
    for _ in range(K):
        if cur==start:
            break
        cur = P[cur]
        scores.append(C[cur]+scores[-1])


    
    #no_loop_sum= max(scores[:K])
    #remain_hops=K-scores.index(no_loop_sum)-1
    #if scores[-1]>0:
    #    loops=remain_hops//len(scores)
    #else:
    #    loops=0
    #ans=max(ans,no_loop_sum+scores[-1]*loops)

    
    for goal in range(len(scores)):
        no_loop_sum=scores[goal]
        #remain_hops=K-goal-1

        remain_hops=K-1


        if scores[-1]>0:
            loops=remain_hops//len(scores)
        else:
            loops=0
        ans=max(ans,no_loop_sum+scores[-1]*loops)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 17:30:06 2020

@author: divyarth
"""

import sys
import heapq
import math

#sys.setrecursionlimit(100000)
#input=sys.stdin.readline
#print=sys.stdout.write

from collections import deque
from collections import defaultdict
from collections import Counter

modH=int(10**9)+7
I=lambda : list(map(int,input().split(' ')))
def PRINT(lst,sep=' '): print(sep.join(map(str,lst)))

n,k=I()
PP=I()
c=I()
graph=[[] for i in range(n)]
for p in range(n):
    graph[p].append(PP[p]-1)
ans=[]
for start in range(n):
    visited=[0 for i in range(n)]
    node=start
    cycle=[]
    while not visited[node]:
        visited[node]=1
        cycle.append(c[node])
        node=graph[node][0]
    num_steps=k
    s=sum(cycle)*(k//len(cycle)) if k//len(cycle)>0 else 0
    
    if s<0:
        num_steps=0
        s=0
    else:
        num_steps=k//len(cycle)
        
    cum_sum=[0]
    for sss in cycle: cum_sum.append(cum_sum[-1]+sss)    
    ns=0
    ss=0
    for j in range(k%len(cycle)):
        if cum_sum[j+1]>ss:
            ss=cum_sum[j+1]
            ns=j
    num_steps+=ns
    if num_steps>=1:
        ans.append(s+ss)
    else:
        ans.append(c[start])
print(max(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()))
lis = [[0] * (N) for _ in range(N+1)]
for i in range(1,N+1):
    for j in range(N):
        lis[i][P[j]-1] = C[P[j]-1] + lis[i-1][j]

ans = -float('inf')
cnt = 0
if N >= K or sum(C) <= 0:
    for l in lis:
        m = max(l)
        ans = max(ans,m)
        cnt +=1
        if cnt == K:
            break

else:
    div,K = divmod(K,N)
    su = sum(C) * div 
    tmp = [su] * N
    lis[0] = tmp
    for l in lis:
        m = max(l)
        ans = max(ans,m)
        if cnt == K:
            break
        cnt += 1
    ans += su

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=-float("inf")

for start in range(N):
    cur=P[start]
    scores=[C[cur]]
    for _ in range(K):
        if cur==start:
            break
        cur = P[cur]
        scores.append(C[cur]+scores[-1])


    
    #no_loop_sum= max(scores[:K])
    #remain_hops=K-scores.index(no_loop_sum)-1
    #if scores[-1]>0:
    #    loops=remain_hops//len(scores)
    #else:
    #    loops=0
    #ans=max(ans,no_loop_sum+scores[-1]*loops)

    
    for goal in range(len(scores)):
        no_loop_sum=scores[goal]
        #remain_hops=K-goal-1

        remain_hops=K


        if scores[-1]>0:
            loops=remain_hops//len(scores)
        else:
            loops=0
        ans=max(ans,no_loop_sum+scores[-1]*loops)
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 = min(C)
for i in range(N) :
    t = 1
    j = P[i]-1
    l = C[j]
    ans = max(ans,l)
    while j != i and K > t:
        j = P[j] - 1
        l += C[j]
        t += 1
        ans = max(ans,l)
    
    if l > 0 and K > t :
        c = (K-t)//t 
        d = K%t
        l += l*c
        ans = max(ans,l)
        for _ in range(d) :
            j = P[j] - 1
            l += C[j]
            ans = max(ans,l)

print(ans)

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 = []
    k = 0
    visited = [-1]*N
    for r in range(N):
        S.append(C[l])
        visited[l] = r
        l = P[l] - 1
        if visited[l] != -1:
            k = r - visited[l] + 1
            break
    r += 1
    S1 = sum(S[r - k:])
    S2 = sum(S[:r - k])
    cnt = (K - (r - k)) // k - (K % k == 0)
    a = (K - (r - k)) %k + (K % k == 0)*k
    for j in range(a):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S1 > 0:
        m1 += cnt*S1 + S2
    m2 = max2(m1, m2)

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

Submission status: Wrong Answer

Solution code:
import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
import copy
INF = 10**9


if __name__ == "__main__":
    n,k = map(int,input().split())
    p = list(map(int,input().split()))
    c = list(map(int,input().split()))
    score = -10**9-10
    
    for i in range(n):
        n_score = c[p[i]-1]
        next_n = p[i]-1
        score = max(score,n_score)
        for j in range(k-1):
            n_score += c[p[next_n]-1]
            next_n = p[next_n]-1
        score = max(score,n_score)
    print(score)

Submission status: Wrong Answer

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

memo = [[]  for i in range(n)]
for i in range(n):
    memo[i].append(C[i])
    j = P[i]
    while True:
        memo[i].append(memo[i][-1] + C[j])
        j = P[j]
        if j == i:
            memo[i].append(memo[i][-1] + C[j])
            break

circles = [memo[i][-1] - memo[i][0] for i in range(n)]

ans = -1e10
for i  in range(n):
    le = (len(memo[i]) - 1)
    m = k // le
    if circles[i] > 0 and m > 0:
        k_ = k % le
        if k_ == 0:
        	alt = max(memo[i][:-1]) + circles[i] * m
        else:
        	alt = max(memo[i][:k_]) + circles[i] * m
        ans = max(alt, ans)
        alt =  max(memo[i][:-1]) + circles[i] * (m-1)
        ans = max(alt, ans)
    else:
        alt =  max(memo[i][:-1])
        ans = max(alt, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect
class UnionFind(): #集合の取り扱い、辺に重み、階層を意識するときは使えない
    def __init__(self,n):
        self.n=n
        self.par = [-1]*n
    def find(self,x):
        if self.par[x] <0: #負なら親、要素数
            return x
        else: #正なら親の番号
            self.par[x]=self.find(self.par[x]) #一回調べたら根を繋ぎ変える、経路圧縮
            return self.par[x]
    def union(self,x,y):
        x=self.find(x) #x,yの親
        y=self.find(y)

        if x==y: #親が同じなら何もしない
            return 
        if self.par[x]>self.par[y]: #要素数が大きい方をxにする
            x,y=y,x
        self.par[x]+=self.par[y] #xがある集合にyが入った集合をくっつける
        self.par[y]=x

    def size(self,x):
        return -self.par[self.find(x)] #親のサイズ
    
    def same(self,x,y): #親が同じ、すなわち同じ集合か
        return self.find(x)==self.find(y)

    def member(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.par) if x<0]
    
    def group_count(self): #集合の数、木の数
        return len(self.roots())

    def all_member(self): #辞書型で返す
        return {r: self.member(r) for r in self.roots()}
    def __str__(self):
        return "\n".join('{}:{}'.format(r,self.member(r)) for r in self.roots)


n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
tree=UnionFind(n)
for i in range(n):
    if p[i]-1 not in set(tree.member(i)):
        tree.union(i,p[i]-1)
finalans=-10**10
for i in tree.roots():
    res=tree.member(i)
    point=[0]*(len(res)*2)
    point[0]=c[res[0]]
    for j in range(1,len(res)*2):
        if j<len(res):
            point[j]=point[j-1]+c[res[j]]
        else:
            point[j]=point[j-1]+c[res[j-len(res)]]
    m=-10**10
    if k<=len(res):
        for j in range(1,k+1):
            for t in range(j-1,j+len(res)-1):
                cand=point[t]-point[t-j] if t-j>=0 else point[t]
                m=max(m,cand)
        ans=m
    else:
        if point[len(res)-1]>0:
            r=k%(len(res))
            if r==0:
                ans=point[len(res)-1]*(k//n)
            else:
                M=-10**10
                for j in range(1,r+1):
                    for t in range(j-1,j+len(res)-1):
                        cand=point[t]-point[t-j] if t-j>=0 else point[t]
                        M=max(M,cand)
                ans=point[len(res)-1]*(k//(len(res)))+M
        else:
            for j in range(1,len(res)+1):
                for t in range(j-1,j+len(res)-1):
                    cand=point[t]-point[t-j] if t-j>=0 else point[t]
                    m=max(m,cand)
            ans=m
    finalans=max(ans,finalans)
print(finalans)

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**29
for start in range(N):
    now = start
    point = 0
    for j in range(K):
        now = P[now]
        point += C[now]
        ans = max(ans, point)
        if now == start:
            break
    loop_cnt = j+1
    left_k = K - loop_cnt
    point *= left_k // loop_cnt + 1
    ans = max(ans, point)
    for j in range(left_k%loop_cnt):
        now = P[now]
        point += C[now]
        ans = max(ans, point)

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 = []
    index = i
    while not reach[index]:
        buf.append(c[index])
        reach[index] = True
        index = p[index]
    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 = r[len(i)-1]*n
    for j in range(len(i)):
        for k in range(1,min(len(i)+1,k+1)):
            s = r[j+k]-r[j]
            if k<ind+1:
                ans = max(ans,a+s)
            ans = max(ans,s)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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]
SB = defaultdict(int)

# Pの要素の中で循環するモノ同士をまとめる
sep = []
visited = [0] * n
for i in range(n):
  s = i
  box = []
  while visited[s] == 0:
    box.append(s)
    visited[s] = 1
    s = P[s]
  if box != []:
    sep.append(box)

ans = - 10 ** 19
for sp in sep:
  sumC = sum([C[i] for i in sp]) 
  sn = len(sp)

  if sumC > 0:
    d, mk = divmod(k, sn)
    if d > 0:
      pscore = (d - 1) * sumC
      mk += sn 
    else:
      pscore = 0
  else:
    mk = min(k, sn * 2)
    pscore = 0

  for p in P: 
    cnt = 0
    score = 0
    mv = - 10 ** 19
    s = p
    while cnt < mk:
      score += C[s]
      s = P[s]
      cnt += 1
      mv = max(mv, score)
    
    SB[p] = mv

  ans = max(ans, max(SB.values()) + pscore)
  
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()))

route = {}
point = {}

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

all_max = point[1]
for origin_start in range(1, N+1):
    visit = set()
    visit.add(origin_start)
    now_point = 0
    max_point = point[origin_start]
    start = origin_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:
            roup_count = k + 1
            if now_point >= 0:
                now_point *= (K // roup_count)
                start = origin_start
                for k in range(K % roup_count):
                    now_point += point[start]
                    max_point = max(max_point, now_point)
                    start = route[start]
            break
        visit.add(start)
    # print(k, now_point, start, K % k)
    # roup_count = k + 1
    # if now_point >= 0:
    #     now_point *= (K // roup_count)
    #     start = origin_start
    #     for k in range(K % roup_count):
    #         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(lambda a: int(a)-1, input().split())))
C = list(map(int,input().split()))
checked = [True] * N
scores = []
res = - 10 ** 60
for i in range(N):
    if checked:
        current = i
        score = []
        while checked[current]:
            checked[current] = False
            Next = P[current]
            score.append(C[Next])
            current = Next
        if len(score) > 0:
            scores.append(score)
for s in scores:
    l = len(s)
    Sum = sum(s)
    s = s+s
    wa = [0] * (l+1)
    kukan = K % l
    loop = K // l
    for kukan in range(1,l+1):
        loop = (K - kukan) % l
        wa = [0] * (l+kukan+1)
        for i in range(l+kukan):
            wa[i+1] = wa[i] + s[i]
        Max = - 10 ** 60
        for i in range(l):
            Max = max(Max,wa[i+kukan]-wa[i])
        res = max(res, Sum * loop + Max,Max)

print(res)

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

p = [i-1 for i in p]
import numpy as np
tuuka_id = []

point_list = []

for mass in range(n):
  score = 0
  scorelist = []
  move_cnt = 0
  st_mass = mass
  if mass in tuuka_id:
    continue
  
  tuuka_id.append(mass)
  while True:
    mass = p[mass]
    #print(mass, c[mass])
    tuuka_id.append(mass)
    score += c[mass]
    scorelist.append( c[mass] )
    move_cnt += 1
    
    if mass == st_mass:
      break
  k_res = k % move_cnt
  if k_res == 0:
    k_res = move_cnt
    
  scorel2 = scorelist + scorelist

  res_val = max([ np.cumsum(scorel2[i:i+k_res]).max() for i in range( len(scorelist) )])
  if k_res == 0:
    point = max(0, score * max(0,(k // move_cnt-1))) + max(0, res_val )
  else:
    point = max(0, score * max(0,(k // move_cnt))) + max(0, res_val)
  point_list.append( point )
print(max(point_list))

Submission status: Wrong Answer

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

ans = - 10 ** 18
for i in range(1, n+1):
    base = i
    nxt = p[i]
    cnt = 0
    score = 0
    while True:
        cnt += 1
        if cnt > k:
            break
        score += c[nxt]
        ans = max(ans, score)
        #print("i = ", i, "ans = ", ans, "score = ", score)
        if nxt == base:
            break
        nxt = p[nxt]
    if cnt >= k:
        continue
    extra = k - cnt
    nxt = p[nxt]
    if extra < cnt:
        for j in range(extra):
            score += c[nxt]
            ans = max(ans, score)
            #print("ans = ", ans, "score_tmp = ", score_tmp, "nxt = ", nxt, "c[nxt] = ", c[nxt])
            nxt = p[nxt]
    else:
        a = extra // cnt
        score += score * a
        ans = max(ans, score)
        for j in range(extra - a * cnt):
            score += c[nxt]
            ans = max(ans, score)
            nxt = p[nxt]

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=-float("inf")

for start in range(N):
    cur=P[start]
    scores=[C[cur]]
    for _ in range(K):
        if cur==start:
            break
        cur = P[cur]
        scores.append(C[cur]+scores[-1])


    
    no_loop_sum= max(scores[:K])
    remain_hops=K-scores.index(no_loop_sum)-1
    if scores[-1]>0:
        loops=remain_hops//len(scores)
    else:
        loops=0
    ans=max(ans,no_loop_sum+scores[-1]*loops)

    
    #for goal in range(len(scores)):
    #    no_loop_sum=scores[goal]
    #    remain_hops=K-goal-1

    #    if scores[-1]>0:
    #        loops=remain_hops//len(scores)
    #    else:
    #        loops=0
    #    ans=max(ans,no_loop_sum+scores[-1]*loops)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(100000)


def main():
    n, k = [int(i) for i in input().strip().split()]
    P = [None] + [int(i) for i in input().strip().split()]
    C = [None] + [int(i) for i in input().strip().split()]
    seen = set()
    loops = []
    score = []
    loop_sums = []
    loop_max = []
    ans = -float("inf")
    if max(C[1:]) < 0:
        ans = max(C[1:])
        print(ans)
        return

    # ループを探す
    for i in range(1, n + 1):
        flag = False
        loop = []
        sc = []
        _sum = 0
        j = i
        if j not in seen:
            flag = True
            while j not in loop:
                loop.append((j))
                sc.append(C[j])
                seen.add(j)
                _sum += C[j]
                j = P[j]
        if flag:
            loops.append(loop)
            loop_sums.append(_sum)
            score.append(sc)

    # 各ループで作れる最大値を出す
    _max = []
    for i in range(len(loops)):
        loop = loops[i]
        sc = score[i]
        _max = -float("inf")
        # 各始点からループを始める
        for j in range(len(loop)):
            # 1周してみる
            _tmp = 0
            for p in range(min(len(loop), k)):
                ptr = (j + p) % len(loop)
                _tmp += sc[ptr]
                _max = max(_max, _tmp)
        # そのループの最大値を記録する
        loop_max.append(_max)
    """
    print("loops", loops)
    print("score", score)
    print("loop_sums", loop_sums)
    print("loop_max", loop_max)
    """
    for i in range(len(loops)):
        loop = loops[i]
        sc = score[i]
        _sum = loop_sums[i]  # ループの合計値
        _max = loop_max[i]  # ループで得られる最大値
        # 周回しないケース
        ans = max(ans, _max)

        # 周回するケース
        loop_sum = _sum * (k // (len(loop)))
        res = k % len(loop)

        # 各始点からループを始める
        _max = -float("inf")
        for j in range(len(loop)):
            # 1周してみる
            _tmp = 0
            # 残ってるホップ回数で作れる最大値を探す
            for p in range(min(len(loop), res)):
                ptr = (j + p) % len(loop)
                _tmp += sc[ptr]
                _max = max(_max, _tmp)
        ans = max(ans, loop_sum + _max)
    print(ans)
    return


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
P = [-1]+list(map(int,input().split()))
C = [-1]+list(map(int,input().split()))
visited = [True]+[False]*n
circles = []
for i in range(1,n+1):
    if not visited[i]:
        pre = i
        visited[i]=True
        s = [C[i]]
        while P[i] != pre:
            s.append(C[P[i]])
            visited[P[i]] = True
            i = P[i]
        circles.append((s,sum(s)))
# print(circles)
anslist = []

for ci in circles:
    ci_ans = 0
    if ci[1] > 0:
        ci_ans += ci[1]*(k//len(ci[0]))
        k//= len(ci[0])
    maxi = -10**9
    for start in range(len(ci[0])):
        ci2 = (ci[0]*2)[start:(start+len(ci[0]))]
        point = 0
        for i in range(min(k,len(ci[0]))):
            point += ci2[i]
            maxi = max(maxi,point)
    ci_ans += maxi
    anslist.append(ci_ans)
print(max(anslist))

Submission status: Wrong Answer

Solution code:
def roop(i,K):
    n=i
    ma=[-1]*N
    ma[n]=0
    point=0
    maxp=-10**30
    cnt=0
    isroop=False
    while cnt<K:
        cnt+=1
        n=P[n]
        point+=C[n]
        ma[n]=point
        maxp=max(maxp,point)
        if n==i:
            isroop=True
            break
    if not isroop:
        return maxp
    
    allpoint=(K//cnt)*point
    K%=cnt
    lastpoint=0
    j=0
    n=i
    point=0
    while(j<K):
       j+=1
       n=P[n]
       point+=C[n]
       lastpoint=max(lastpoint,point)
    return max([allpoint+lastpoint,allpoint-point+maxp,maxp])

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):
    ans=max(ans,roop(i,K))
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()))

route = {}
point = {}

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

all_max = point[1]
for origin_start in range(1, N+1):
    visit = set()
    visit.add(origin_start)
    now_point = 0
    max_point = point[origin_start]
    start = origin_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)
    roup_count = k + 1
    if now_point >= 0:
        now_point *= (K // roup_count)
        start = origin_start
        for k in range(K % roup_count):
            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()))
ans=-10**10
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 len(temp)>=K+1:
    ans=max(ans, max(temp[1:K+1]))
    continue
  if temp[-1]<=0:
    ans = max(ans, (max(temp[1:])))
  elif K%(len(temp)-1)!=0:
    t=temp[-1]*(K//(len(temp)-1))
    t+=max(temp[:1+K%(len(temp)-1)])
    ans=max(ans, t)
  else:
    t=temp[-1]*(K//(len(temp)-1))-temp[-1]
    t+=max(temp)
    ans=max(ans,t)
		
print(int(ans))

Submission status: Wrong Answer

Solution code:
from copy import copy

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

itta_list = [0] * N
path_list = []
c_list = []
path = []
c = []
now = 0
while sum(itta_list) != N:
    now = P[now] - 1
    if itta_list[now] == 0:
        path.append(now)
        c.append(C[now])
        itta_list[now] = 1
    else:
        path_list.append(path)
        for i in range(len(c)):
            c.append(c[i])
        c_list.append(c)
        path = []
        c = []
        now = itta_list.index(0)
path_list.append(path)
for i in range(len(c)):
    c.append(c[i])
c_list.append(c)

ans = []
for i in range(len(path_list)):
    path = path_list[i]
    c = c_list[i]
    N2 = len(path)

    score = 0
    K2 = copy(K)
    if K > N2:
        sho = K // N2
        yo = K % N2
        K2 = yo
        if sum(c[0: N2]) > 0:
            score += sum(c[0: N2]) * sho

    m = -10 ** 9
    for k in range(K2):
        for n in range(N2):
            m = max(sum(c[n: n + k + 1]), m)
    ans.append(m + score)

print(max(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()))
mx=-float("inf")


for i in range(n):

  sc=0
  pn=i
  mass=[0]*n
  for j in range(k):
    if mass[pn]!=0:
      lpk=j-mass[pn][0]
      amari=(k-(j+1))%lpk
      lpsc=sc-mass[pn][1]
      for l in range(amari+1):
        pn=p[pn]-1
        sc+=c[pn]
        mx=max(mx,sc)
      sc+=lpsc*((k-j-amari)//lpk)
      mx=max(mx,sc)
      #print(lpk,j,amari)
      break
    mass[pn]=[j,sc]
    pn=p[pn]-1
    sc+=c[pn]
    
    mx=max(mx,sc)
  #print(mass)
print(mx)

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

DP=[[C[P[n]]] for n in range(N)]

for start in range(N):
    visited=set()
    cur=P[start]
    while cur not in visited:
        visited.add(cur)
        cur = P[cur]
        DP[start].append(C[cur]+DP[start][-1])


for n in range(N):
    DP[n]=DP[n][:-1]

ans=-float("inf")

for start in range(N):
    #pattern1(先に進んでからloopする)

    no_loop_max=max(DP[start][:K])
    remain_hops=K-DP[start].index(no_loop_max)-1

    if DP[start][-1]>0:
        loop_cnt=remain_hops//len(DP[start])
    else:
        loop_cnt=0
    tmp_ans=no_loop_max+loop_cnt*DP[start][-1]

    ans=max(ans,tmp_ans)
print(ans)

Submission status: Wrong Answer

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

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

# 各点からスタートして、
# (1)得点の累計
# (2)ループするまでの各点までの最高点
# (3)ループするのに必要な回数
# (4)ループしきったときの得点変化
# を記録
# 得点変化が正のときは、できるだけループした上で、残り回数を使って(2)より最高点を求める

ans = -(10 ** 10)
for i in range(N): # スタート
  now = i
  point_sum = 0
  best = []
  cnt = 0
  while True:
    #if i >= 7:
      #print("i",i,"now",now)
    cnt += 1
    point_sum += C[now]
    if len(best) == 0:
      best.append(point_sum)
    else:
      best.append(max(best[-1], point_sum))
    now = P[now]
    if now == i:
      break
  #if i >= 7:
    #print("i",i,"からスタートすると",cnt,"回でループし、ループでの得点は",point_sum)
    #print("3回の移動の得点の最大値は",best)
  point = 0
  if point_sum > 0:
    point += point_sum * (K // cnt)
  rest = K % cnt
  #if i >= 7:
    #print("残り",rest,"回移動することが出来、その時の最大得点は、",best[rest])
  point += best[rest - 1]
  if ans < point:
    ans = point
  #print("i",i,"ans",ans)

print(ans)