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

done = [0]*n

def cycle(st):
    global done
    visited = [0]*n
    visited[st] = 1
    idx = P[st]
    cyc = 0
    sco = [0]
    for _ in range(n):
        done[idx] += 1
        visited[idx] += 1
        cyc += 1
        sco.append(sco[-1] + C[idx])
        if visited[idx] > 1: break
        else: idx = P[idx]
    return cyc, sco

ans = -10**18

for i in range(n):
    #if done[i] > 0: continue

    cyc, sco = cycle(i)

    if sco[-1] > 0:
        # 繰り返したほうが得
        d, m = divmod(k, cyc)
        v = d * sco[-1] + max(sco[:m+1])
        #v = d * sco[-1] + (max(sco) - min(sco))
    else:
        # 早期打ち切り
        v = max(sco[1:])
        #v = max(sco) - min(sco)

    ans = max(ans, v)
    #print(i, cyc, sco, v)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
l=[]
vis=[0]*n
ans=0
flag=0
for i in range(n):
    vis=[0]*n
    q=[i]
    c1=[c[i]]
    t=0
    while True:
        a=q[-1]
        vis[a]=1
        if vis[p[a]-1]==1:
            t=p[a]-1
            break
        else:
            q.append(p[a]-1)
            c1.append(c[p[a]-1])
    m=0
    m1=-c1[0]
    flag1 = 0
    for j in range(len(q)):
        if q[j]==t or j>k:
            break
        m1+=c1[j]
        if m1 >= 0:
            flag1 += 1
        m=max(m1,m)
    t1=m1
    if j<=k:
        for j1 in range(j,min(len(q),k+1)):
            m1 += c1[j1]
            m = max(m1, m)
            if m1>=0:
                flag1+=1
        s=sum(c1[j:])
        t1+=((k+1-j)//(len(q)-j))*s
        if t1 >= 0:
            flag = 2
        m1=0
        m2=0
        for j1 in range(j,j+(k+1-j)%(len(q)-j)):
            m1+=c1[j1]
            m2=max(m1,m2)
        t1+=m2
        m=max(m,t1)
    flag=max(flag,flag1)
    ans=max(ans,m)
if flag<2:
    ans=-INF
    for i in range(n):
        ans=max(ans,c[p[i]-1])
out(ans)

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 _ in range(K):
    next = Ps[next]
    cycle += Cs[next]
    steps.append(cycle)
    if next == i:
      if cycle>0:
        if K%len(steps)!=0:
          now = (K//len(steps))*cycle+max(steps[:K%len(steps)])
          if now>res:
            res = now
          break
        else:
          now =(K//len(steps))*cycle
          if now>res:
            res = now
          break
      else:
        now = max(steps)
        if now>res:
          res = now
        break
    if len(steps)==K:
      now = max(steps)
      if now>res:
        res = now
print(res)

Submission status: Wrong Answer

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


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

ans=-1*(10**10)

if K<10000000:
    for i in range(N):
        tmp=0
        pos=i
        count=0
        while count<K:    
            #print(pos,P[pos])
            tmp+=C[P[pos]-1]
            if tmp>ans:
                ans=tmp
            
            pos=P[pos]-1
            count+=1
     
    print(ans)
else:
    
    for i in range(N):
        tmp=0
        pos=i
        gpos=i
        count=0
        while count<K:    
            #print(pos,P[pos])
            tmp+=C[P[pos]-1]
            if tmp>ans:
                ans=tmp
            
            
            pos=P[pos]-1
            count+=1
            if pos==gpos and count!=K:
                divide=K//count
                tmp=tmp*divide
                count=count*divide
                gpos=10**10
            
    
    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()))

score = [0 for _ in range(n)]
loopn = [0 for _ in range(n)]
done = {i: True for i in range(n)}
for start in range(n):
    if done[start]:
        nex = -1
        j = 0
        tuuka = []
        nax = -float("inf")
        while nex != start:
            if nex == -1:
                nex = P[start]-1
            else:
                nex = P[nex]-1
            tuuka.append(nex)
            score[start] += C[nex]
            nax = max(nax, score[start])
            j += 1
        loopn[start] = j
        for i in tuuka:
            done[i] = False
            loopn[i] = j
            score[i] = score[start]
            nokori = k-(k//loopn[start])*loopn[start]

    if score[start] < 0:
        score[start] = 0
    else:
        score[start] = (k//loopn[start])*score[start]
        nokori = k-(k//loopn[start])*loopn[start]
        i = 0
        nnnnn = (k//loopn[start])
        nscore = 0
        nax = 0
        while i < nokori:
            nex = P[nex]-1
            nscore += C[nex]
            if nscore < 0:
                break
            nax = max(nax, nscore)
            i += 1
        if nax > 0:
            score[start] += nax


ans = max(score)
if ans <= 0:
    ans = max(C)
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()))

P = [0] + P
C = [0] + C

ans = -10**17
Loop = []
LoopValue = []
LoopCount = []

for i in range(1, n+1):
    if i in []:
        pass
    else:
        Visited = []
        Value = [0]
        count = 0
        pos = P[i]
        while pos != i:
            Visited.append(pos)
            Value.append(Value[-1] + C[pos])
            count += 1
            pos = P[pos]
        Visited.append(i)
        count += 1
        Value.append(Value[-1] + C[pos])
        Loop.append(Visited)
        LoopValue.append(Value)
        LoopCount.append(count)
        
        
        if k//count == 0:
            tmp = max(Value[1:k%count + 1])
        else:
            tmp = max(max(Value[1:]), k//count*Value[-1] + max(Value[:k%count + 1]))
        ans = max(tmp, ans)
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()))

max_score = -1000000000
for i in range(n):
    score = 0
    count = 0
    start = p[i]-1
    now = start
    for _ in range(k):
        score += c[now]
        max_score = max(max_score,score)
        now = p[now]-1
        count += 1
        if now == start:
            if score < 0:
                break
            else:
                m = k // count
                max_score = score * m
print(max_score)

Submission status: Wrong Answer

Solution code:
n, limit = list(map(int, input().split()))
permute = list(map(int, input().split()))
score = list(map(int, input().split()))

visited = [False] * n

ans = -10 ** 16

for i in range(n):
    if visited[i]:
        continue

    score_circle = []
    now = i
    while True:
        visited[now] = True
        score_circle.append(score[now])

        next_ = permute[now] - 1
        if visited[next_]:
            # 円環のできあがり
            break
        now = next_
    
    period = len(score_circle)

    score_circle *= 2
    # 累積和
    cumsum = [0] * (2 * period + 1)
    for j in range(1, 2*period+1):
        cumsum[j] = cumsum[j-1] + score_circle[j-1]
    
    p_sum_max = [-(10**15)] * (period + 1)
    for k in range(period):
        for ll in range(period):
            p_sum_max[ll] = max(p_sum_max[ll], cumsum[k+ll] - cumsum[k])
    
    ans = max([ans] + p_sum_max[1:min(period+1, limit+1)])

    q, resi = divmod(limit, period)

    if q >= 1:
        ans = max(ans, cumsum[period] * (q-1) + max(p_sum_max))
        ans = max(ans, cumsum[period] * (q) + max(p_sum_max[:resi + 1]))

        # print(p_sum_max[:resi + 1])

print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import combinations
from collections import Counter
import math
import numpy as np
from copy import deepcopy


def main():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    p_rev = [0] * n
    for i in range(len(p)):
        p_rev[p[i] - 1] = i
    num_list = list(range(n))
    search_list = [list(range(n)), list(range(n))]
    c = list(map(int, input().split()))

    dp = [[0] * n for i in range(k + 1)]

    loop_idx = None
    for i in range(1, k + 1):
        search_list[0] = deepcopy(search_list[1])
        for j in range(n):
            dp[i][j] = dp[i - 1][p_rev[j]] + c[j]
            search_list[1][j] = search_list[0][p_rev[j]]
        if num_list == search_list[1]:
            loop_idx = i
            break

    if loop_idx is None:
        print(np.max(dp[1:]))
    else:
        loop_flag = False
        for i in range(n):
            if dp[loop_idx][i] > 0:
                loop_flag = True
                break

        if loop_flag:
            t = k // loop_idx
            base = [x * t for x in dp[loop_idx]]
            for i in range(1, k + 1):
                for j in range(n):
                    dp[i][j] += base[j]

        print(np.max(dp[1:loop_idx]))


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()))
score0=0
score1=0
score2=0
scoremax=0
if k<n:
  for i in range(n):
    nexti=p[i]-1
    score2=c[nexti]
    score1=score2
    score0=score2
    for j in range(i,k):
      nexti=p[nexti-1]-1
      score0+=c[nexti]
      if score0>score1:
        score1=score0
        if score1>score2:
          score2=score1
        scoremax=max(scoremax,score0)
      else:
        if score1>score2:
          score2=score1
          scoremax=max(scoremax,score1)
        else:
          scoremax=max(scoremax,score2)
          break
else:
  times=0
  for i in range(n):
    nexti=p[i]-1
    score2=c[nexti]
    score1=score2
    score0=score2
    for j in range(i,n):
      nexti=p[nexti-1]-1
      score0+=c[nexti]
      if score0>score1:
        score1=score0
        if score1>score2:
          score2=score1
        if score0>scoremax:
          scoremax=score0
      else:
        if score1>score2:
          score2=score1
          scoremax=max(scoremax,score1)
        else:
          scoremax=max(scoremax,score2)
          break
print(scoremax)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))
    m = max(C)
    if m <= 0:
        print(m)
        exit()
    i, c = 0, 0
    G = []
    g = []
    v = [False] * n
    while c < n:
        if v[i]:
            G.append(g)
            g = []
            i = v.index(False)
        g.append(i)
        v[i] = True
        i = P[i] - 1
        c += 1
    if g != []:
        G.append(g)
    ans = 0
    for g in G:
        score = [C[gg] for gg in g]
        S = [0] + list(accumulate(score * 2))
        ln = len(score)
        p = k % ln
        c = max(0, sum(score)) * (k // ln)
        l, r = 0, 1
        while l <= ln:
            if r - l > p:
                l += 1
                r = l + 1
            ans = max(ans, S[r] - S[l] + c)
            r += 1
        l, r = 0, 1
        while l <= ln:
            if r - l > ln:
                l += 1
                r = l + 1
            ans = max(ans, S[r] - S[l])
            r += 1


    print(ans)






if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

p_in = [0 for _ in range(n)]
p_in = [int(s) for s in input().split()]

c_in = [0 for _ in range(n)]
c_in = [int(s) for s in input().split()]
p = {}
c = {}

for i in range(n):
    p[i+1] = p_in[i]
    c[i+1] = c_in[i]




init_p = 1

def solve(init_p,n,k):
    
    def get_key_from_value(d, val):
        keys = [gg for gg, v in d.items() if v == val]
        if keys:
            return keys[0]
        return None
    
    pst = init_p
    pnt = 0
    flag = 0

    pnt_log = {}
    pst_log = {}
    pst_log[0] = pst
    pnt_log[0] = pnt
    for i in range(k):
        pst = p[pst]
        pnt += c[pst]

        if(pst in pst_log.values()):
            pst_key = get_key_from_value(pst_log,pst)
            b_pnt = pnt_log[pst_key]
            n_pnt = pnt
            num_l = i
            num = i - pst_key
            flag = 1
            break

        pst_log[i+1] = pst
        pnt_log[i+1] = pnt
    
    print(pnt_log,flag)
    if(flag == 0):
        #print("hi")
        ans = max(pnt_log.values())
        return ans
    
    if(b_pnt > n_pnt):
        ans = max(pnt_log.values())
        return ans
    else:
        xx = k // num
        if(xx < 1 and k - num > 0):
            for j in range(k - num):
                pst = p[pst]
                pnt += c[pst]
                pst_log[num_l + j] = pst
                pnt_log[num_l + j] = pnt
                ans = max(pnt_log.values())
                return ans
            
        else:
            pnt = pnt + (xx - 1)*abs(b_pnt - n_pnt)
            k = k - (xx-1)*num
            for j in range(k - num):
                pst = p[pst]
                pnt += c[pst]
                pst_log[num_l + j] = pst
                pnt_log[num_l + j] = pnt
                ans = max(pnt_log.values())
                return ans
            
init_p = 1

mx = (-1)*2**30 
for ff in range(n):
    hh = solve(init_p,n,k)
    print(hh,mx)
    if(hh):
        mx = max(mx,hh)

print(mx)

Submission status: Wrong Answer

Solution code:
from itertools import chain

N, K = map(int, input().split())
P_L = [int(x)-1 for x in input().split()]
C_L = [int(x) for x in input().split()]

s_l = [[0] * N for _ in range(N+1)]
ts_l = [[0] * (N+1) for _ in range(N)]

for i in range(N):
    _p = i
    for j in range(1, N+1):
        _p = P_L[_p]
        s_l[j][i] = s_l[j-1][i] + C_L[_p]
        ts_l[i][j] = ts_l[i][j-1] + C_L[_p]
s_l[0] = [float("-Inf")] * N
ts_l[0] = [float("-Inf")] * (N+1)

if K <= N:
    _l = list(chain(*(s_l[:K+1])))
    print(max(_l))
else:
    if max(s_l[N]) <= 0:
        _l = list(chain(*s_l))
        print(max(_l))
    else:
        _c = K // N
        _n = K % N
        ans = float("-Inf")
        for i in range(N):
            _tmp = s_l[N][i]
            _ans_a = _tmp * _c + max(ts_l[i][:_n+1])
            _ans_b = _tmp * (_c - 1) + max(ts_l[i])
            ans = max(ans, _ans_a, _ans_b)
        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()))
t=0
if K>N and sum(C)>0:
  t=sum(C)*(K//N)
ans=max(C)
r=min(N,K%N)
for i in range(N):
  print(i,ans)
  next=P[i]-1
  s=C[next]
  ans=max(ans,s)
  for _ in range(r):
    next=P[next]-1
    s+=C[next]
    ans=max(ans,s)
print(ans+t)

Submission status: Wrong Answer

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


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

ans=-1*(10**10)

if K<100000:
    for i in range(N):
        tmp=0
        pos=i
        count=0
        while count<K:    
            #print(pos,P[pos])
            tmp+=C[P[pos]-1]
            if tmp>ans:
                ans=tmp
            
            pos=P[pos]-1
            count+=1
     
    print(ans)
else:
    
    for i in range(N):
        tmp=0
        pos=i
        gpos=i
        count=0
        while count<K:    
            #print(pos,P[pos])
            tmp+=C[P[pos]-1]
            if tmp>ans:
                ans=tmp
            
            
            pos=P[pos]-1
            count+=1
            if pos==gpos and count!=K:
                divide=K//count
                tmp=tmp*divide
                count=count*divide
                gpos=10**10
            
    
    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()))

s = -10**10
l = k % 5000
m = k // 5000
tc = sum(c)

for i in range(n):
    e = 0
    f = -10**10
    d = p[i]
    for j in range(l):
        e = e + c[d-1]
        d = p[d-1]
        if f < e:
            f = e
    if s < f:
        s = f

ans = m * tc + s

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] = P[i] - 1

used = [False] * N

ans = 0
for i in range(N):
    if not used[i]:
        arr = []
        j = i
        while True:
            arr.append(C[j])
            used[j] = True
            j = P[j]
            if i == j:
                break
            
        #print(arr)
        l = 0
        res = 0
        s = 0
        for j in range(len(arr)):
            if l < K & s + arr[j] > arr[j]:
                s = s + arr[j]
                l = l + 1
            else:
                s = arr[j]
                l = 1
            res = max(res, s);

        ans = max(ans, res)
        
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

v = [False] * n
roop = []

for i in range(n):
    if not v[i]:
        tmp = [i]
        while True:
            t = p[tmp[-1]]
            v[t] = True
            if tmp[0] == t:
                break
            else:
                tmp.append(t)
        roop.append(tmp)

s = []

for li in roop:
    s1 = 0
    for i in li:
        s1 += c[i]
    s.append(s1)

s2 = []

for li in roop:
    tmp = [0]
    for i in li:
        tmp.append(tmp[-1] + c[i])
    for i in li:
        tmp.append(tmp[-1] + c[i])
    s2.append(tmp)

v2 = [-1] * n

for i,li in enumerate(roop):
    for j in li:
        v2[j] = i

ans = -10**18

for i,li in enumerate(roop):
    t = -10**18
    if s[i] <= 0:
        for j in range(len(li)):
            for k1 in range(j+1, j + 1 + min(k, len(li))):
                t = max(t, s2[i][k1] - s2[i][j])
        ans = max(ans, t)
    else:
        cnt = k // len(li)
        if cnt == 0:
            for j in range(len(li)):
                for k1 in range(j+1, j + 1 + min(k, len(li))):
                    t = max(t, s2[i][k1] - s2[i][j])
            ans = min(ans, t)
        else:
            for j in range(len(li)):
                for k1 in range(j+1, j + 1 + len(li)):
                    t = max(t, s2[i][k1] - s2[i][j] + s[i] * (cnt - 1))
            for j in range(len(li)):
                for k1 in range(j+1, j + 1 + (k % len(li))):
                    t = max(t, s2[i][k1] - s2[i][j] + s[i] * cnt)
            ans = max(ans, t)

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

score_map = [[0] * 5100 for i in range(5100)]

for i in range(n):
    current = i
    score = 0
    for j in range(n):
        current = p[current] - 1
        score += c[current]
        score_map[i][j] = score

ans = max(c)
if n >= k:
    for i in range(n):
        ans = max(ans, max(score_map[i][:k]))
else:
    if sum(c) <= 0:
        for i in range(n):
            ans = max(ans, max(score_map[i][:k]))
    else:
        q, m = divmod(k, n)
        for i in range(n):
            ans = max(ans, max(score_map[i][: m + 1]))
        ans += sum(c) * q
print(ans)

Submission status: Wrong Answer

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


def read():
    N, K = map(int, input().strip().split())
    P = [0] + list(map(int, input().strip().split()))
    C = [0] + list(map(int, input().strip().split()))
    return N, K, P, C


def solve(N, K, P, C):
    max_score = -10**9
    for i in range(1, N+1):
        # 途中までのスコアの最大値をとるための移動距離
        d = 0
        # 途中までのスコアの最大値
        inter_score = -10**7
        # 1周の長さ
        size = 0
        # 1周のスコアの最大値
        round_score = -10**7
        j = i
        score = 0
        while True:
            size += 1
            score += C[P[j]]
            j = P[j]
            if score > inter_score:
                inter_score = score
                d = size
            if i == j:
                break
        round_score = score
        if K < d:
            continue
        else:
            max_score = max(max_score, inter_score)
        if K < size:
            continue
        else:
            max_score = max(max_score, round_score)
        # 周回してみる
        if round_score > 0 and K >= size:
            if K % size <= d:
                base_score = round_score * (K // size)
                k = K % size
                j = i
                while k >= 0:
                    max_score = max(max_score, base_score)
                    base_score += C[P[j]]
                    j = P[j]
                    k -= 1
            else:
                max_score = max(max_score, round_score * (K // size))
    return max_score


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
def main():
    n, ko = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    dummy = [-1]
    p = tuple(dummy + p)
    c = tuple(dummy + c)
    shoki = 10**9 + 1
    scores = [-shoki] * (n + 1)

    for i1 in range(1, n + 1):
        k = ko
        kita = [-1] * (n + 1)
        kita[i1] = 0
        score = [-shoki] * (n + 1)
        cnt = 0
        koko = i1
        score_ima = c[koko]
        while k:
            cnt += 1
            k -= 1
            koko = p[koko]
            score_ima += c[koko]
            if kita[koko] >= 0:
                cycle = cnt - kita[koko]
                mawarukaisuu = k // cycle
                k -= cycle * mawarukaisuu
                if score_ima > score[koko]:
                    score_cycle = score_ima - score[koko]
                    score_ima += mawarukaisuu * score_cycle
                    score[koko] = score_ima
                while k:
                    k -= 1
                    koko = p[koko]
                    score_ima += c[koko]
                    score[koko] = score_ima
                else:
                    score[koko] = score_ima
            else:
                kita[koko] = cnt
                score[koko] = score_ima
        tmp = max(score)
        if tmp == 0:
            scores[i1] = c[i1]
        else:
            scores[i1] = tmp

    print(max(scores))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

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


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

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

ans = -INF
for i in range(N):
    for j in range(min(K, 5005)):
        ans = max(ans, points[i][j])
    val = points[i][cnt_loop[i] - 1]
    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)

# MAX_LOG = 35
# nx = [[0] * N for _ in range(MAX_LOG)]
# nx[0] = P
# points = [[0] * N for _ in range(MAX_LOG)]

# for i in range(N):
#     points[0][i] = C[P[i]]

# for k in range(MAX_LOG - 1):
#     for i in range(N):
#         nx[k + 1][i] = nx[k][nx[k][i]]
#         points[k + 1][i] = points[k][i] + points[k][nx[k][i]]
# print(nx)
# ans = 0

Submission status: Wrong Answer

Solution code:
import sys

def main():
    input = sys.stdin.readline
    n, k = map(int, input().split())
    p = list(map(lambda x:int(x) - 1, input().split()))
    c = list(map(int, input().split()))
    seen = [0] * n
    accumulate = []
    for i in range(n):
        if seen[i] == 0:
            accumulate.append([c[i]])
            pre = i
            while True:
                if seen[pre] == 1:
                    accumulate[-1].pop()
                    break
                seen[pre] = 1
                now = p[pre]
                pre = now
                accumulate[-1].append(accumulate[-1][-1] + c[now])
    
    ans = -float("INF")
    for lst in accumulate:
        if len(lst) >= k:
            for interval in range(1, k):
                for start in range(len(lst)):
                    if start + interval >= len(lst):
                        num = lst[-1] + lst[(start + interval) % len(lst)] - lst[start]                    
                    else:
                        num = lst[(start + interval)] - lst[start]
                    ans = max(ans, num)
        else:
            if lst[-1] > 0:
                for interval in range(1, len(lst)):
                    for start in range(len(lst)):
                        num = (k - interval) // len(lst) * lst[-1]
                        if start + interval >= len(lst):
                            num += (lst[-1] + lst[(start + interval) % len(lst)] - lst[start])                    
                        else:
                            num += (lst[(start + interval)] - lst[start])
                        ans = max(ans, num)
                """
                for interval in range(1, k - len(lst) * (k // len(lst)) + 1):
                    for start in range(len(lst)):
                        num = (k // len(lst)) * lst[-1]
                        if start + interval >= len(lst):
                            num += (lst[-1] + lst[(start + interval) % len(lst)] - lst[start])
                        else:
                            num += lst[(start + interval)] - lst[start]
                        ans = max(ans, num)
                """
            else:
                for interval in range(1, len(lst)):
                    for start in range(len(lst)):
                        if start + interval >= len(lst):
                            num = lst[-1] + lst[(start + interval) % len(lst)] - lst[start]                    
                        else:
                            num = lst[(start + interval)] - lst[start]
                        ans = max(ans, num)
            
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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


res1 = k//n
res2 = k%n
d = [0]*n

if sum(c)<0:
  for i in range(n):
    x = p[i]
    ans = 0
    res3 = 0
    for j in range(n):
      res3 += c[x-1]
      x = p[x-1]
      ans = max(ans, res3)
    if d[i] <= ans:
      d[i] = ans
else:
  for i in range(n):
    d[i] += res1*sum(c)
    x = p[i]
    ans = 0
    res3 = 0
    for j in range(n):
      res3 += c[x-1]
      x = p[x-1]
      ans = max(ans, res3)
    if d[i] <= ans:
      d[i] += ans
      
print(max(d))