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: Runtime Error

Solution code:
N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
S = []
R = -1000000001
#それぞれについての累積和の計算
for i in range(N):#このループはN個の初期マスの時のループ
    t = i  # tは現在の位置
    cnt = 0  # 累積和
    sum = []  # 累積和のリスト
    res = 0
    while True:#このループは一つの初期マスの累積和。最初のコマに戻るまで
        cnt += C[P[t]-1]
        t = P[t]-1
        sum.append(cnt)
        if t == i:
            break
    #S.append(sum)
    if len(sum) >=  K:
        res = max(sum[:K])
    else:
        if sum[-1] <= 0:
            res = max(sum)
        else:
            score1 = sum[-1] * (K // len(sum) - 1) + max(sum)
            score2 = sum[-1] * (K // len(sum)) + max(sum[0:K % len(sum)])
            res = max(score1,score2)
    R = max(R,res)
print(R)

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
S = []
R = -float("inf")
#それぞれについての累積和の計算
for i in range(N):#このループはN個の初期マスの時のループ
    t = i  # tは現在の位置
    cnt = 0  # 累積和
    sum = []  # 累積和のリスト
    res = 0
    while True:#このループは一つの初期マスの累積和。最初のコマに戻るまで
        cnt += C[P[t]-1]
        t = P[t]-1
        sum.append(cnt)
        if t == i:
            break
    #S.append(sum)
    if len(sum) >=  K:
        res = max(sum[:K])
    else:
        if sum[-1] <= 0:
            res = max(sum)
        else:
            score1 = sum[-1] * (K // len(sum) - 1) + max(sum)
            score2 = sum[-1] * (K // len(sum)) + max(sum[0:K % len(sum)])
            res = max(score1,score2)
    R = max(R,res)
    print(sum)
print(R)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ttl=[]
cnt=[]
count=0
for i in range(n):
  nxt=i+1
  grp=[]
  count=0
  pnt=[]
  pnt.append(0)
  for j in range(n):
    nxt=p[nxt-1]
    pnt.append(pnt[j]+c[nxt-1])
    count+=1
    if nxt==i+1:
      del pnt[0]
      ttl.append(pnt)
      cnt.append(count)
      break
ans=[]
for i in range(n):
  peak=ttl[i].index(max(ttl[i]))
  if k<=cnt[i]:
    ans.append(max(ttl[i][:k]))
  else:
    if ttl[i][-1]<0:
      ans.append(ttl[i][peak])
    else:
      ans.append(max((k//cnt[i])*ttl[i][-1]+max(ttl[i][0:k%cnt[i]]),((k-peak-1)//cnt[i])*ttl[i][-1]+ttl[i][peak]))
print(max(ans))

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
ans = -10 ** 10
 
if  n >= k:
    for i in range(n):
        score = 0
        z = p[i] - 1
        for j in range(k):
            score += c[z]
            z = p[z] - 1
            ans = max(ans, score)
 
else:
    frag = []
    cyc = []
    for i in range(n):
        total = []
        tot = 0
        tol = - 10 * 10
        cyc_i = []
        z = p[i] - 1
        for j in range(n):
            tot += c[z]
            cyc_i.append(c[z])
            tol = max(tol, tot)
            total.append(tot)
            if p[i] == p[z]:
                break
            z = p[z] - 1
        frag.append(total)
        cyc.append(cyc_i)
    for i in range(n):
        if sum(cyc[i]) <= 0:
            ans = max(ans, tol)
        else:
            x = k // len(cyc[i])
            w = k % len(cyc[i])
            score = (sum(cyc[i]) * x) + frag[i][w - 1]
            ans = max(ans, score)
            for j in range(len(cyc[i])-1):
                if w >= j:
                    score -= cyc[i][w - 1 - j]
                else:
                    score -= cyc[i][len(cyc[i]) + w - j]
                ans = max(ans, score)
    
print(ans)
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
ans = -10 ** 10
 
if  n >= k:
    for i in range(n):
        score = 0
        z = p[i] - 1

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
ans = -10 ** 10
 
for i in range(n):
    tot = []
    t = 0
    z = p[i] - 1
    for j in range(n):
        t += c[z]
        tot.append(t)
        if i == z:
            break
        z = p[z] - 1
    if k <= len(tot):
        score = max(tot[:k])
    elif tot[-1] <= 0:
        score = max(tot)
    else:
        x = k // len(tot)
        w = k % len(tot)
        score = tot[-1] * (k // len(tot) - 1) + max(tot)
        score = -10 * 10
        if w > 1:
            score1 = tot[-1] * (k // len(tot)) + max(tot[:(w -1)])
        elif w == 1:
            score1 = tot[-1] * (k // len(tot)) + tot[0]
        score = max(score, score1)
    ans = max(ans, score)
    
print(ans)

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
ans = -10 ** 10
 
for i in range(n):
    tot = []
    t = 0
    z = p[i] - 1
    for j in range(n):
        t += c[z]
        tot.append(t)
        if i == z:
            break
        z = p[z] - 1
    if k <= len(tot):
        score = max(tot[:k])
    elif tot[-1] <= 0:
        score = max(tot)
    else:
        x = k // len(tot)
        w = k % len(tot)
        score = tot[-1] * (k // len(tot) - 1) + max(tot)
        if w > 0:
            score1 = tot[-1] * (k // len(tot)) + max(tot[:(w -1)])
            score = max(score, score1)
    ans = max(ans, score)
    
print(ans)

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
ans = -10 ** 10
 
for i in range(n):
    tot = []
    t = 0
    z = p[i] - 1
    for j in range(n):
        if i == z:
            break
        t += c[z]
        tot.append(t)
        z = p[z] - 1
    if k <= len(tot):
        score = max(tot[:k])
    elif tot[-1] <= 0:
        score = max(tot)
    else:
        x = k // len(tot)
        w = k % len(tot)
        score = tot[-1] * (k // len(tot) - 1) + max(tot)
        if w > 0:
            score1 = tot[-1] * (k // len(tot)) + max(tot[:(w -1)])
            score = max(score, score1)
    ans = max(ans, score)
    
print(ans)

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
ans = -10 ** 10
 
for i in range(n):
    tot = []
    t = 0
    z = p[i] - 1
    for j in range(n):
        if i == z:
            break
        t += c[z]
        tot.append(t)
        z = p[z] - 1
    if k <= len(tot):
        score = max(tot[:k])
    elif tot[-1] <= 0:
        score = max(tot)
    else:
        x = k // len(tot)
        w = k % len(tot)
        score1 = tot[-1] * (k // len(tot) - 1) + max(tot)
        score2 = tot[-1] * (k // len(tot)) + max(tot[:(w -1)])
        score = max(score1, score2)
    ans = max(ans, score)
    
print(ans)

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
 
ans = -10 ** 10
 
if  n >= k:
    for i in range(n):
        score = 0
        z = p[i] - 1
        for j in range(k):
            score += c[z]
            z = p[z] - 1
            ans = max(ans, score)
 
else:
    for i in range(n):
        tot = []
        t = 0
        z = p[i] - 1
        for j in range(n):
            if i == z:
                break
            t += c[z]
            tot.append(t)
            z = p[z] - 1
        if tot[-1] <= 0:
            score = max(tot)
        else:
            x = k // len(tot)
            w = k % len(tot)
            score1 = tot[-1] * (k // len(tot) - 1) + max(tot)
            score2 = tot[-1] * (k // len(tot)) + max(tot[:(w -1)])
            score = max(score1, score2)
        ans = max(ans, score)
    
print(ans)

Submission status: Runtime Error

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

from itertools import accumulate

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

INF = 1 << 60
ans = []


def solve(n, k, p, c):
    checked = [False] * n
    cycle = []

    for i in range(n):
        if checked[i]:
            continue
        scores = [c[i]]
        nxt = p[i]
        checked[i] = True
        while nxt != i:
            scores.append(c[nxt])
            nxt = p[nxt]
        cycle = scores * 3
        length = len(cycle)

        if sum(cycle) < 0:
            for i in range(length):
                tmp_arr = cycle[i:i + min(length, k)]
                ans.append(max(list(accumulate(tmp_arr))))
        else:
            div, mod = divmod(k, length)
            add_cycle = div * sum(cycle)
            for i in range(length):
                tmp_arr = cycle[i:i + mod]
                ans.append(max(list(accumulate(tmp_arr))) + add_cycle)
    return ans


print(max(solve(n, k, p, c)))

Submission status: Runtime Error

Solution code:
from itertools import accumulate

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

INF = 1 << 60
ans = -INF


checked = [False] * n
cycle = []

for i in range(n):
    if checked[i]:
        continue
    scores = [c[i]]
    nxt = p[i]
    checked[i] = True
    while nxt != i:
        scores.append(c[nxt])
        nxt = p[nxt]
    cycle = scores * 3
    length = len(cycle)

    if sum(cycle) < 0:
        for i in range(length):
            tmp_arr = cycle[i:i + min(length, k)]
            ans = max(ans, max(list(accumulate(tmp_arr))))
    else:
        div, mod = divmod(k, length)
        add_cycle = div * sum(cycle)
        for i in range(length):
            tmp_arr = cycle[i:i + mod]
            ans = max(ans, max(list(accumulate(tmp_arr))) + add_cycle)

print(ans)

Submission status: Runtime Error

Solution code:
from itertools import accumulate

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

INF = 1 << 60
ans = -INF


checked = [False] * n
cycle = []

for i in range(n):
    if checked[i]:
        continue
    scores = []
    nxt = p[i]
    visited = []
    checked[i] = True
    while nxt not in visited:
        visited.append(nxt)
        scores.append(c[nxt])
        nxt = p[nxt]
    cycle = scores * 3
    length = len(cycle)

    if sum(cycle) < 0:
        for i in range(length):
            tmp_arr = cycle[i:i + min(length, k)]
            ans = max(ans, max(list(accumulate(tmp_arr))))
    else:
        div, mod = divmod(k, length)
        add_cycle = div * sum(cycle)
        for i in range(length):
            tmp_arr = cycle[i:i + mod]
            ans = max(ans, max(list(accumulate(tmp_arr))) + add_cycle)

print(ans)

Submission status: Runtime Error

Solution code:
from itertools import accumulate

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

INF = 1 << 60
ans = -INF


checked = [False] * n
cycle = []

for i in range(n):
    if checked[i]:
        continue
    scores = []
    nxt = p[i]
    visited = []
    while nxt not in visited:
        visited.append(nxt)
        scores.append(c[nxt])
        nxt = p[nxt]
    cycle = scores * 3
    length = len(cycle)

    if sum(cycle) < 0:
        for i in range(length):
            tmp_arr = cycle[i:i + min(length, k)]
            ans = max(ans, max(list(accumulate(tmp_arr))))
    else:
        div, mod = divmod(k, length)
        add_cycle = div * sum(cycle)
        for i in range(length):
            tmp_arr = cycle[i:i + mod]
            ans = max(ans, max(list(accumulate(tmp_arr))) + add_cycle)

print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - 10000000000
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    ans = max(ans, max(tmp[:K]))
    else:
        v = (tmp[-1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)

Submission status: Runtime Error

Solution code:
class UnionFind():
    n=1
    par=[0]
    rnk=[0]
    def __init__(self,size):
        self.n=size
        self.par=[i for i in range(self.n)]
        self.rnk=[0 for i in range(self.n)]
    def find(self,vertex1):
        if self.par[vertex1]==vertex1:
            return vertex1
        else:
            self.par[vertex1]=self.find(self.par[vertex1])
            return self.par[vertex1]
    def unite(self,vertex1,vertex2):
        vertex1=self.find(vertex1)
        vertex2=self.find(vertex2)
        if vertex1==vertex2:
            return
        if (self.rnk[vertex1]<self.rnk[vertex2]):
            self.par[vertex1]=vertex2
        else:
            self.par[vertex2]=vertex1
            if(self.rnk[vertex1]==self.rnk[vertex2]):
                self.rnk[vertex1]+=1
    def same(self,vetrex1,vertex2):
        return self.find(vetrex1)==self.find(vertex2)

N,K=map(int,input().split())
P=[int(i)-1 for i in input().split()]
C=[int(i) for i in input().split()]
G=UnionFind(N)
for i in range(N):
    G.unite(i,P[i])
D=dict()
for i in range(N):
    if G.find(i) in D:
        D[G.find(i)]+=1
    else:
        D[G.find(i)]=1

dp=[[0 for j in range(N)] for i in range(N+1)]
for j in range(N):
    dp[0][j]=j
for i in range(N):
    for j in range(N):
        dp[i+1][j]=P[dp[i][j]]
#1 3 4 0 2
#0->1->3->0, 2->4->2
score=[[0 for j in range(N)] for i in range(N)]
for i in range(N):
    for j in range(N):
        score[i][j]=score[i-1][j]+C[dp[i+1][j]]
def maxpoint(j,L):
    if L<=N:
        return max([score[i][j] for i in range(L)])
    else:
        roop=D[G.find(j)]
        cyclepoint=score[roop-1][j]
        if cyclepoint<0:
            return maxpoint(j,roop)
        else:
            return maxpoint(j,L%roop)+(L//roop)*cyclepoint
ans=[maxpoint(j,K) for j in range(N)]
print(max(ans))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - float('inf')
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    if tmp[-1] < 0:
        ans = max(ans, max(tmp))
    else:
        v = (tmp[-1] * (K // j)) + max(tmp[:K % j])
        ans = max(ans, v)
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - float('inf')
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    if tmp[-1] < 0:
        ans = max(ans, max(tmp))
    else:
        v = (tmp[-1] * (K // j)) + max(tmp[:K % j])
        ans = max(ans, v)
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ttl=[]
cnt=[]
count=0
for i in range(n):
  nxt=i+1
  grp=[]
  count=0
  pnt=[]
  pnt.append(0)
  for j in range(n):
    nxt=p[nxt-1]
    grp.append(nxt)
    pnt.append(pnt[j]+c[nxt-1])
    count+=1
    if nxt==i+1:
      del pnt[0]
      ttl.append(pnt)
      cnt.append(len(grp))
      break
ans=[]
for i in range(n):
  peak=ttl[i].index(max(ttl[i]))
  if k<=cnt[i]:
    ans.append(max(ttl[i][:k]))
  else:
    if ttl[i][-1]<0:
      ans.append(max(ttl[i][:k]))
    else:
      ans.append(max((k//cnt[i])*ttl[i][-1]+max(ttl[i][0:k%cnt[i]]),((k-peak)//cnt[i])*ttl[i][-1]+ttl[i][peak]))
print(max(ans))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ttl=[]
cnt=[]
count=0
for i in range(n):
  nxt=i+1
  grp=[]
  count=0
  pnt=[]
  pnt.append(0)
  for j in range(n):
    nxt=p[nxt-1]
    grp.append(nxt)
    pnt.append(pnt[j]+c[nxt-1])
    count+=1
    if nxt==i+1:
      del pnt[0]
      ttl.append(pnt)
      cnt.append(len(grp))
      break
      
ans=[]
for i in range(n):
  peak=ttl[i].index(max(ttl[i]))
  if k<=cnt[i]:
    ans.append(max(ttl[i][:k]))
  else:
    if ttl[i][-1]<0:
      ans.append(max(ttl[i][:k]))
    else:
      ans.append(max((k//cnt[i])*ttl[i][-1]+max(ttl[i][:k%cnt[i]]),((k-peak)//cnt[i])*ttl[i][-1]+ttl[i][peak]))
print(max(ans))

Submission status: Runtime Error

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

vis = [0 for i in range(n+1)]
	

res = -10000000000000000000000
for i in range(0,n):
	if vis[i] == 0:
		su = 0
		vis[i] = 1
		v = []
		v.append(C[i])
		su += C[i]
		x = P[i]
		while x != i:
			vis[x] = 1
			su += C[x]
			v.append(C[x])
			x = P[x]
		vs = len(v)
		for ii in range(vs):
			umm = 0
			for j in range(vis):
				x = (ii+j)%vs
				umm += v[x]
				steps = 1+(x-ii+vs)%vs
				if k >= vs:
					if(su > 0):
						r = max((k-steps)//vs,0)
						res = max(res, r*su + umm)
					else:
						res = max(res,umm)
				else:
					if steps <= k:
						res = max(res,umm)


print(res)

Submission status: Runtime Error

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

ans = -10 ** 10

if  n >= k:
    for i in range(n):
        score = 0
        z = p[i] - 1
        for j in range(k):
            score += c[z]
            z = p[z] - 1
            if ans <= score:
                ans = score

else:
    for i in range(n):
        row = 0
        z = p[i] - 1
        for j in range(n):
            row += 1
            if p[i] == p[z]:
                break
            z = p[z] - 1
    for i in range(n):
        x = k // row
        z = p[i] - 1
        tol = 0
        total = -10 * 10
        frag = []
        for j in range(row):
            tol += c[z]
            z = p[z] - 1
            if tol >= total:
                total = tol
            frag.append(tol)
        if tol[row] > 0:
            x = k // row
            w = k % row
            score = (tol * x) + frag[w - 1]
            if ans<= score:
                ans = score
            z = p[i] - 1
            for l in range(row-1):
                score -= c[z]
                z = p[z] - 1
                if ans <= score:
                    ans = score
        else:
            if ans <= total:
                ans = total
    
print(ans)

Submission status: Runtime Error

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 = []
    j = p[i]-1 
    s.append(c[j])
    while j != i:
        j = p[j]-1
        s.append(s[-1]+c[j])
    l = len(s)
    if k <= l:
        a = max(s[:k])
    elif s[-1] <= 0:
        a = max(s)
    else:
        w, r = divmod(k, l)
        a1 = s[-1]*(w-1) + max(s)
        a2 = s[-1]*w + max(0, max(s[:r]))
        a = max(a1, a2)
    ans = max(ans, a)
print(ans)

Submission status: Runtime Error

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

def loop(tugi,con,i):
    if(tugi-1 in loop_check or K<=con):
        #print('b')
        return 0

    else:
        con=con+1
        #loop_check=
        #print('a')
        #print(tugi)
        loop_check.append(tugi-1)
        #print(C[tugi-1])
        #print(P[tugi-1])
        #'''
        #a=loop(P[tugi-1])
        loop_num_list[i].append(C[P[tugi-1]-1])
        return C[P[tugi-1]-1]+loop(P[tugi-1],con,i)
loop_num_list=[]
#print(loop_num_list)
loop_num=[]
loop_check=[]
for i in range(N):
    loop_num_list.append([])
    #print(loop_num_list)
    loop_num.append(loop(i+1,0,i))
    loop_check=[]
#print(loop_num)
#print()
#print(loop_num_list)
#print(max(loop_num))
print(loop_num_list)
print(loop_num)
b_max=-10**10
for i in range(len(loop_num_list)):
    c=-10**10
    cc=0
    if(0<loop_num[i]):
        a=K//len(loop_num_list[i])
        b=a*loop_num[i]
        for j in range(K%len(loop_num_list[i])):
            cc=cc+loop_num_list[i][j]
            c=max(c,cc)
        b=b+c
        b_max=max(b,b_max)
    else:
        for j in range(len(loop_num_list[i])):
            cc=cc+loop_num_list[i][j]
            c=max(c,cc)
        b_max=max(c,b_max)

print(b_max)

Submission status: Runtime Error

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

def loop(tugi,con,i):
    if(tugi-1 in loop_check or K<=con):
        #print('b')
        return 0

    else:
        con=con+1
        #loop_check=
        #print('a')
        #print(tugi)
        loop_check.append(tugi-1)
        #print(C[tugi-1])
        #print(P[tugi-1])
        #'''
        #a=loop(P[tugi-1])
        loop_num_list[i].append(C[P[tugi-1]-1])
        return C[tugi-1]+loop(P[tugi-1],con,i)
loop_num_list=[]
#print(loop_num_list)
loop_num=[]
loop_check=[]
for i in range(N):
    loop_num_list.append([])
    #print(loop_num_list)
    loop_num.append(loop(i+1,0,i))
    loop_check=[]
#print(loop_num)
#print()
#print(loop_num_list)
#print(max(loop_num))
b_max=-10**10
for i in range(len(loop_num_list)):
    c=-10**10
    cc=0
    if(0<loop_num[i]):
        a=K//len(loop_num_list[i])
        b=a*loop_num[i]
        for j in range(K%len(loop_num_list[i])):
            cc=cc+loop_num_list[i][j]
            c=max(c,cc)
        b=b+c
        b_max=max(b,b_max)
    else:
        for j in range(len(loop_num_list[i])):
            cc=cc+loop_num_list[i][j]
            c=max(c,cc)
        b_max=max(c,b_max)

print(b_max)

Submission status: Runtime Error

Solution code:
from numba import njit
@njit(parallel=True)
def main():
  n,k=map(int,input().split())
  p=list(map(int,input().split()))
  c=list(map(int,input().split()))
  ans=-10**18
  for i in range(n):
    start,count=i,1
    val=c[start]
    while p[start]-1!=i: #ループ部分
      start=p[start]-1
      count+=1
      val+=c[start]
    start=i
    if val>0:
      a=(k//count-1)*val #一周目はループのどの部分から始めるのが最適かわからないので
      ans=max(a,ans)
      num=count+k%count
    else:
      a=0
      num=min(k,count)
    for _ in range(num):
      start=p[start]-1
      a+=c[start]
      ans=max(a,ans)
  print(ans)
main()

Submission status: Runtime Error

Solution code:
from numba import njit
@njit
def main():
  n,k=map(int,input().split())
  p=list(map(int,input().split()))
  c=list(map(int,input().split()))
  ans=-10**18
  for i in range(n):
    start,count=i,1
    val=c[start]
    while p[start]-1!=i: #ループ部分
      start=p[start]-1
      count+=1
      val+=c[start]
    start=i
    if val>0:
      a=(k//count-1)*val #一周目はループのどの部分から始めるのが最適かわからないので
      ans=max(a,ans)
      num=count+k%count
    else:
      a=0
      num=min(k,count)
    for _ in range(num):
      start=p[start]-1
      a+=c[start]
      ans=max(a,ans)
  print(ans)
main()

Submission status: Runtime Error

Solution code:
# D - Moving Piece 

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

# スタート位置をN通り試す
ans = 10 ** 18 * -1
for i in range(N):
    # とりあえずKステップ進めてみて、
    # ループが発生するかどうか
    tot = 0
    cnt = 0
    now = i
    nxt = now
    arr = []
    tmp = C[P[nxt] - 1]
    for j in range(1, K+1):
        cnt += 1
        nxt = P[nxt] - 1
        tot += C[nxt]
        tmp = max(tmp, tot)
        arr.append(tot)
        if j == K:
            ans = max(ans, tmp)
            break
        if now == nxt:
            if tot >= 0:
                tmp = tot * (K // cnt)
                m = K % cnt
                if m != 0:
                    tmp += max(arr[:m])
                ans = max(ans, tmp)
            else:
                m = K % cnt
                tmp = max(arr[:m])
                ans = max(ans, tmp)
            break
print(ans)

Submission status: Runtime Error

Solution code:
# D - Moving Piece 

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

# スタート位置をN通り試す
ans = 10 ** 18 * -1
for i in range(N):
    # とりあえずKステップ進めてみて、
    # ループが発生するかどうか
    tmp = 0
    tot = 0
    cnt = 0
    now = i
    nxt = now
    arr = []
    for j in range(1, K+1):
        cnt += 1
        nxt = P[nxt] - 1
        tot += C[nxt]
        tmp = max(tmp, tot)
        arr.append(tot)
        if now == nxt:
            if tot >= 0:
                tmp = tot * (K // cnt)
                m = K % cnt
                tmp += max(arr[:m])
                ans = max(ans, tmp)
            else:
                m = K % cnt
                tmp = max(arr[:m])
                ans = max(ans, tmp)
            break
        if j == K:
            ans = max(ans, tmp)
            break
print(ans)

Submission status: Runtime Error

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N, K = LI()
    P = LI_()
    C = LI()

    ans = -INF
    for i in range(N):
        # iを含むサイクルの探索
        cycle = []
        c = i
        while True:
            c = P[c]
            cycle.append(c)
            if c == i:
                break
        len_cycle = len(cycle)

        # 最大スコアの探索
        score = 0

        # Kの残り
        r = K
        cycle_score_total = sum([C[j] for j in cycle])
        if len_cycle < K:
            # 周回して増えるなら周回する
            if cycle_score_total > 0:
                score += K // len_cycle * cycle_score_total
                # 周回後の余り
                r = K % len_cycle
            # 周回して増えないなら周回しない
            else:
                # サイクル一周までの範囲でどこまでもいける
                r = len_cycle

        # Kの残っている範囲で最大スコア探索
        cycle_score = [C[j] for j in cycle[:r]]
        cycle_score_cum = list(itertools.accumulate(cycle_score))
        score += max(cycle_score_cum)

        ans = max(score, ans)

    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N, K = LI()
    P = LI_()
    C = LI()

    ans = -INF
    for i in range(N):
        # iを含むサイクルの探索
        cycle = []
        c = i
        while True:
            c = P[c]
            cycle.append(c)
            if c == i:
                break
        len_cycle = len(cycle)

        # 最大スコアの探索
        score = 0

        # Kの残り
        r = K
        cycle_score_total = sum([C[j] for j in cycle])
        if len_cycle < K:
            # 周回して増えるなら周回する
            if cycle_score_total > 0:
                score += K // len_cycle * cycle_score_total
                # 周回後の余り
                r = K % len_cycle
            # 周回して増えないなら周回しない
            else:
                # サイクル一周までの範囲でどこまでもいける
                r = len_cycle

        # Kの残っている範囲で最大スコア探索
        cycle_score = [C[cycle[j]] for j in range(r)]
        # cycle_score_cum = list(itertools.accumulate(cycle_score))
        cycle_score_cum = [0] * r
        cycle_score_cum[0] = cycle_score[0]
        for i in range(r - 1):
            cycle_score_cum[i+1] = cycle_score[i+1] + cycle_score_cum[i]
        score += max(cycle_score_cum)

        ans = max(score, ans)

    print(ans)

if __name__ == '__main__':
    resolve()