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: Time Limit Exceeded

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

ans = -1*float('inf')

for i in range(N):
    k = i
    Cc = []
    Ct = 0
    while 1:
        k = P[k]-1
        Cc.append(C[k])
        if i == k:
            break
    l = len(Cc)
    Ct = sum(Cc)
    t = 0
    for j in range(l):
        t += Cc[j]
        if j >= K:break
        now = t
        if Ct > 0:
            e = (K-j-1)//l
            now +=  Ct*e
        ans = max(ans,now)
print(ans)

Submission status: Time Limit Exceeded

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
for i in range(N):
    nx = i
    total = 0
    L = [] 
    while True:
        nx = P[nx]
        total += C[nx]
        L.append(C[nx])
        if nx == i:
            break
    l = len(L)
    now = 0
    for j in range(l):
        if j + 1 > K:
            break
        now += L[j]
        ans = max(ans, now)
    if total > 0:
        now = total * (K // l)
        ans = max(ans, now)
        r = K % l
        for j in range(r):
            now += L[j]
            ans = max(ans, now)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from numba import jit
@jit
def execute():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))

    max_score = -10**100

    for i in range(n):
        point, count = i+1, 0
        val = 0
        while (count < k):
          point = p[point-1]
          val += c[point-1]
          max_score = max(max_score, val)
          count += 1

    print(max_score)

if __name__ == "__main__":
    execute()

Submission status: Time Limit Exceeded

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

    max_score = -10**100

    for i in range(n):
        point, count = i+1, 0
        val = 0
        while (count < k):
          point = p[point-1]
          val += c[point-1]
          max_score = max(max_score, val)
          count += 1

    print(max_score)

if __name__ == "__main__":
    execute()

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split()) # 2 ≤ N ≤ 5000  ; 1 ≤ K ≤ 10^9
P = list(map(int,input().split()))
C = list(map(int,input().split())) # −10^9 ≤ C[i] ≤ 10^9

ring_P = []

def get_score(PP):
    max_score = K * -10**9
    #score = [0] * K
    #score_sum = 0
    for j in range(K):
        score_sum = 0
        for h in range(j+1):
            score_sum += C[PP[(h) % len(PP)]-1]
#        score[j] = score_sum
        max_score = max(max_score, score_sum)
        score_0 = score_sum
        for i in range(1,len(PP)):
            #score_0 = score[j]
            ind_1  = PP[(i+j) % len(PP)]
            ind_0  = PP[(i-1) % len(PP)]
            score_1p = C[PP[(i+j) % len(PP)]-1]
            score_1m = C[PP[(i-1) % len(PP)]-1]
            score_1 = score_0 + (C[PP[(i+j) % len(PP)]-1] - C[PP[(i-1) % len(PP)]-1])
            #score[j] = max(score_0, score_1)
            max_score = max(max_score, score_1)
            score_0 = score_1
    return max_score

max_score = K * -10**9
Arr = [0] * (N+1)
i = 1
while i < N+1:
    if Arr[i] != 1:
        ring_P.append([])
        PP = ring_P[-1]
        Arr[i] = 1
        init = i
        i = P[i-1]
        #print(i)
        PP.append(i)
        while init != i:
            Arr[i] = 1
            i = P[i-1]
            #print(i)
            PP.append(i)
        #print(PP)
        #print([C[i-1] for i in PP])
        #print(get_score(PP))
        max_score = max(get_score(PP),max_score)
    i += 1
#print(ring_P)
print(max_score)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
c.insert(0, 0); p.insert(0, 0)
ans = min(c)
for i in range(1, n+1):
    temp = i
    cnt = 0
    for j in range(k):
        temp = p[temp]
        cnt+=c[temp]
        ans = max(ans, cnt)
print(ans)

Submission status: Time Limit Exceeded

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

# 一度たずねた場所はループが判明しているのでそのままにする(何度移動させるかに関係なくtree構造がつながっているかを調べたい)
ans = -10 ** 18
for i in range(N):
    x = i
    loop = []
    total = 0
    while True:
        x = P[x] - 1
        loop.append(C[x])
        total += C[x]
        if x == i:
            break

    T = len(loop)
    tmp = 0
    for j in range(T):
        tmp += loop[j]
        if K < j + 1:
            break
        now = tmp
        # 一周のループが正の時のみ何度も回す価値がある。それ以外のときはそれまでの最大をとる
        if total > 0:
            loop_times = (K - (j + 1)) // T
            now += total * loop_times

        ans = max(ans, now)
print(ans)

Submission status: Time Limit Exceeded

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

dummy=set()
loop=[]
X=set(range(N))
while len(dummy)!=N:
  a=[]
  k=min(X-dummy)
  a.append(k)
  dummy.add(k)
  l=P[k]-1
  while l!=k:
    a.append(l)
    dummy.add(l)
    l=P[l]-1
  loop.append(a)

ans=-(10**300)
for l in loop:
  temp=0
  s=len(l)
  ssum=0
  k=0
  for i in range(s):
    ssum+=C[l[i]]
  if ssum>0:
    temp+=((K-1)//s)*ssum
    k=K-((K-1)//s)*s
  else:
    k=min(K,s)
  kmax=-(10**300)
  for ii in range(s):
    tempscore=temp
    for jj in range(1,k+1):
      tempscore+=C[l[(ii+jj)%s]]
      if tempscore>kmax:
        kmax=tempscore
  if kmax>ans:
    ans=kmax
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


def solve(N, K, P, L):
    ans = np.iinfo(np.int64).min

    for i in range(N):
        score_acc = np.array([L[i]], dtype=np.int64)
        cur = P[i] - 1
        while cur != i:
            score_acc = np.append(score_acc, [L[cur]])
            cur = P[cur] - 1
        score_acc = np.cumsum(score_acc)
        M = len(score_acc)
        if M < K and score_acc[-1] > 0:
            res = K // M * score_acc[-1]
            if K % M:
                res += max(score_acc[: K % M])
            else:
                res += -score_acc[-1] + max(score_acc)
            ans = max(ans, res)
        else:
            res = max(score_acc[:K])
            ans = max(ans, res)
    return ans


N, K = map(int, input().split())
P = np.array(input().split(), dtype=np.int32)
L = np.array(input().split(), dtype=np.int32)
print(solve(N, K, P, L))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from numba import njit


@njit("i8(i4,i4,i4[:],i4[:])")
def solve(N, K, P, L):
    ans = -np.iinfo(np.int64).min

    for i in range(N):
        score_acc = np.array([L[i]], dtype=np.int64)
        cur = P[i] - 1
        while cur != i:
            score_acc = np.append(score_acc, [L[cur]])
            cur = P[cur] - 1
        score_acc = np.cumsum(score_acc)
        M = len(score_acc)
        if M < K and score_acc[-1] > 0:
            res = K // M * score_acc[-1]
            if K % M:
                res += max(score_acc[: K % M])
            else:
                res += -score_acc[-1] + max(score_acc)
            ans = max(ans, res)
        else:
            res = max(score_acc[:K])
            ans = max(ans, res)
    return ans


N, K = map(int, input().split())
P = np.array(input().split(), dtype=np.int32)
L = np.array(input().split(), dtype=np.int32)
print(solve(N, K, P, L))

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
P = [int(t) - 1 for t in input().split()]
C = list(map(int,input().split()))

ans = -1e18
for si in range(N):
    x = si
    s = []
    tot = 0
    while True:
        x = P[x]
        s.append(C[x])
        tot += C[x]
        if x == si:
            break
    l = len(s)
    t = 0
    for i in range(l):
        t += s[i]
        if i+1 > K:
            break
        now = t
        if tot > 0:
            e = (K-(i+1))//l
            now += tot*e
        if ans < now:
            ans = now
print(ans)

Submission status: Time Limit Exceeded

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

dummy=set()
loop=[]
X=set(range(N))
while len(dummy)!=N:
  a=[]
  k=min(X-dummy)
  a.append(k)
  dummy.add(k)
  l=P[k]-1
  while l!=k:
    a.append(l)
    dummy.add(l)
    l=P[l]-1
  loop.append(a)

ans=-(10**300)
for l in loop:
  temp=0
  s=len(l)
  ssum=0
  k=0
  for i in range(s):
    ssum+=C[l[i]]
  if ssum>0:
    temp+=((K-1)//s)*ssum
    k=K-((K-1)//s)*s
  else:
    k=min(K,s)
  kmax=-(10**300)
  for ii in range(1,k+1):
    for jj in range(s):
      tempscore=temp
      for kk in range(ii):
        tempscore+=C[l[(jj+kk)%s]]
      if tempscore>kmax:
        kmax=tempscore
  if kmax>ans:
    ans=kmax
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
P = [i-1 for i in P]
ans = -1e18
for si in range(N):
    x = si
    s = []
    tot = 0
    while True:
        x = P[x]
        s.append(C[x])
        tot += C[x]
        if x == si:
            break
    l = len(s)
    t = 0
    for i in range(l):
        t += s[i]
        if i+1 > K:
            break
        now = t
        if tot > 0:
            e = (K-(i+1))//l
            now += tot*e
        ans = max(ans,now)
print(ans)

Submission status: Time Limit Exceeded

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

def func1(lc, n):
    l = lc + lc
    res = -10**10
    for i in range(len(lc)):
        res = max(res, max([sum(l[i:i+x]) for x in range(1, n+1)]))
    return res

def func2(lc, m):
    l = lc + lc
    res = -10**10
    for i in range(len(lc)):
        res = max(res, max([sum(l[i:i+x]) + sum(l[i+len(lc)-m:i+len(lc)]) for x in range(1, len(lc)+1)]))
    return res

s = set()
l_res = []

for i in range(n):
    if i in s:
        continue
    l_cur = [i]
    cur = lp[i]
    while cur != i:
        l_cur.append(cur)
        cur = lp[cur]
    s.update(l_cur)
    l_len = len(l_cur)
    l_c = [lc[x] for x in l_cur]
    l_sum = sum(l_c)
    if l_sum <= 0:
        l_res.append(func1(l_c, min(k, l_len)))
    else:
        if l_len >= k:
            l_res.append(func1(l_c, k))
        else:
            l_res.append((k//l_len - 1)*l_sum + func2(l_c, k%l_len))
            
print(max(l_res))

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from collections import deque
    n, k = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))
    P = list(map(lambda x: x - 1, P))
    ans = -10**16
    for i in range(n):
        s = deque([])
        x = i
        tot = 0
        while True:
            x = P[x]
            s.append(C[x])
            tot += C[x]
            if x == i:
                break

        l = len(s)
        t = 0
        for j in range(l):
            t += s[j]
            if j + 1 > k:
                break
            now = t
            if tot > 0:
                e = (k - j - 1) // l  # 何周できるか
                now += tot * e
            ans = max(ans, now)

    print(ans)

resolve()

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
P = [i-1 for i in P]
ans = -1e18
for si in range(N):
    x = si
    s = []
    tot = 0
    while True:
        x = P[x]
        s.append(C[x])
        tot += C[x]
        if x == si :
            break
    l = len(s)
    t = 0
    for i in range(l):
        t += s[i]
        if i+1 > K:
            break
        now = t
        if tot > 0:
            e = (K-i-1)//l
            now += tot*e
        ans = max(ans,now)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N, K = MAP()
P = LIST()
C = LIST()

check = [0]*N 
score = []

i = 0
while 1:
	while i < N and check[i]:
		i += 1
	if i == N:
		break

	tmp = []
	while check[i] == 0:
		check[i] = 1
		i = P[i]-1
		tmp.append(C[i])
	score.append(tmp)

ans = -INF
for x in score:
	x_acc = list(accumulate([0] + x + x))
	n = len(x)
	tmp_max = -INF

	cnt = 0
	p, q = 0, 0
	for i, j in combinations(range(2*n+1), 2):
		if j-i <= min(K, n):
			if tmp_max < x_acc[j]-x_acc[i]:
				tmp_max = x_acc[j]-x_acc[i]
				cnt = j-i
				p, q = i, j


	tmp_ans = -INF
	lis = x[(q-1)%n+1:]+x[:(q-1)%n+1]

	if 0 >= x_acc[n]:
		tmp_ans = tmp_max

	else:
		if cnt <= K%n:
			tmp_ans = x_acc[n]*(K//n) + tmp_max
		else:
			tmp_max2 = 0
			for i, j in combinations(range(2*n+1), 2):
				if j-i <= K%n:
					if tmp_max2 < x_acc[j]-x_acc[i]:
						tmp_max2 = x_acc[j]-x_acc[i]
			tmp_ans = max(x_acc[n]*(K//n-1)+tmp_max, x_acc[n]*(K//n) + tmp_max2)

	ans = max(ans, tmp_ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
def main():
    N, K = map(int, input().split())
    P = [int(x) - 1 for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = -10 ** 9
    for start in range(N):
        # ループを探す
        now = start
        loop = []
        total = 0
        while now != start or not loop:
            loop.append(C[now])
            now = P[now]
            total += C[now]
        # ループごとの最大スコアを探す
        length = len(loop)
        # sum_loop = sum(loop)
        # # ループ長よりも操作回数が多いか？，ループを周回すると得か？で場合分け
        # res = 0 if sum_loop <= 0 else sum_loop * (K // length)
        # limit = K if K <= length else K % length
        # for k in range(limit):
        #     res += loop[k]
        #     ans = max(ans, res)
        t = 0
        for i in range(length):
            t += loop[i]
            if i + 1 > K:
                break
            now = t
            if total > 0:
                e = (K - (i + 1)) // length
                now += total * e
            ans = max(ans, now)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    n, k = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))
    P = list(map(lambda x: x - 1, P))
    ans = -10**16
    for i in range(n):
        s = []
        x = i
        tot = 0
        while True:
            x = P[x]
            s.append(C[x])
            tot += C[x]
            if x == i:
                break

        l = len(s)
        t = 0
        for j in range(l):
            t += s[j]
            if j + 1 > k:
                break
            now = t
            if tot > 0:
                e = (k - j - 1) // l  # 何周できるか
                now += tot * e
            ans = max(ans, now)

    print(ans)

resolve()

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
P = [i-1 for i in P]
ans = -1e18
for si in range(N):
    x = si
    s = []
    tot = 0
    while True:
        x = P[x]
        s.append(C[x])
        tot += C[x]
        if x == si :
            break
    l = len(s)
    t = 0
    for i in range(l):
        t += s[i]
        if i+1 > K:
            break
        now = t
        if tot > 0:
            e = (K-i-1)//l
            now += tot*e
        if ans < now:
            ans = now
        else:
            ans = ans
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

# input
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

# calc
ans = -int(1e18)
for si in range(n):
    x = si
    s = []
    opscore = 0 
    while True:
        x = p[x]
        opscore += c[x]
        s.append(c[x])
        if x == si: 
            break

    oplen = len(s)
    t = 0 
    for i in range(oplen):
        t += s[i]
        if i+1 > k:
            break
        now = t 
        if opscore > 0:
            e = (k-(i+1))//oplen
            now += opscore * e 
        ans = max(ans, now)

print(ans)

Submission status: Time Limit Exceeded

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

ans = -(10 ** 18)

for si in range(N):
    x = si
    loop = []
    total = 0
    while 1:
        x = P[x]
        loop.append(C[x])
        total += C[x]
        if x == si:
            break
    T = len(loop)  # 周期の大きさ
    tmp = 0
    for i in range(T):
        tmp += loop[i]
        if K < i + 1:
            break
        now = tmp
        if total > 0:  # loopの和が正ならloopを回した方がお得
            loop_times = (K - (i + 1)) // T  # 何周できるか
            now += total * loop_times
        ans = max(ans, now)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, k =map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
roop = []
seen = [0 for  _ in range(n)]
count = 0
for i in range(n):
    if seen[i]>0:
        continue
    else:
        count+=1
        seen[i] = count
        roop.append([c[i]])
        t = i
        while i!=p[t]-1:
            seen[p[t]-1]=count
            roop[-1].append(c[p[t]-1])
            t = p[t]-1
#print(seen)
#print(roop)
ans = max(c)
for i in roop:
    ii = i+i
    if len(i)>=k:
        for j in range(1, k+1):
            for l in range(len(i)):
                temp = sum(ii[l:l+j])
                #print(i, j, l, temp)
                ans  = max(ans, temp)
    else:
        for j in range(1, len(i)+1):
            for l in range(len(i)):
                if sum(i)>0:
                    temp = sum(ii[l:l+j])+(sum(i)*((k-j)//len(i)))
                else:
                    temp = sum(ii[l:l+j])
                #print(i, j, l, temp)
                ans  = max(ans, temp)
            
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    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):
        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
            if a > ans:
                ans = a
            num = k%count+count
        else:
            a = 0
            num = min(k, count)

        for j in range(num):
            start = p[start]-1
            a += c[start]
            if a > ans:
                ans = a
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
def main(n, k, p, c):
    ans = -float('inf')
    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 = k%count+count
        else:
            a = 0
            num = min(k, count)

        for j in range(num):
            start = p[start]-1
            a += c[start]
            ans = max(ans, a)
    return ans

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

print(main(n, k, p, c))

Submission status: Time Limit Exceeded

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):
	loop=[0]
	now=i
	while True:
		now=p[now]-1
		loop.append(loop[-1]+c[now])
		if now==i:
			break
	L=len(loop)-1
	if k<=L:
		score=max(loop[1:k+1])
		ans=max(score,ans)
	else:
		score=max(loop[-1],0)*(k//L-1)
		ans=max(ans,score)
		for j in range(k%L+L):
			score+=loop[j%L+1]-loop[j%L]
			ans=max(score,ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    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):
        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 = k%count+count
        else:
            a = 0
            num = min(k, count)

        for j in range(num):
            start = p[start]-1
            a += c[start]
            ans = max(ans, a)
    return ans
print(main())

Submission status: Time Limit Exceeded

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):
    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 = k%count+count
    else:
        a = 0
        num = min(k, count)

    for j in range(num):
        start = p[start]-1
        a += c[start]
        ans = max(ans, a)
print(ans)

Submission status: Time Limit Exceeded

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

n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
check=[-1]*n
finalans=-10**20
for i in range(n):
    if check[i]!=-1:
        continue
    loop=[i]
    now=i
    while p[now]!=i+1:
        loop.append(p[now]-1)
        now=p[now]-1
    L=len(loop)
    point=[0]*(L*2)
    point[0]=c[loop[0]]
    for j in range(1,L*2):
        if j<L:
            point[j]=point[j-1]+c[loop[j]]
        else:
            point[j]=point[j-1]+c[loop[j-L]]
    m=-10**20
    if point[L-1]>0:
        r=k%L
        if r==0:
            r=L
        for j in range(1,r+1):
            for t in range(j-1,j+L-1):
                cand=point[t]-point[t-j] if t-r>=0 else point[t]
                m=max(m,cand)
        ans=point[L-1]*(k//L)+m if r!=L else point[L-1]*((k//L)-1)+m
    else:
        for j in range(1,L+1):
            for t in range(j-1,j+L-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: Time Limit Exceeded

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):
    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
        if a > ans:
            ans = a
        for j in range(k%count+count):
            start = p[start]-1
            a += c[start]
            if a > ans:
                ans = a
    else:
        a = 0
        for j in range(min(k, count)):
            start = p[start]-1
            a += c[start]
            if a > ans:
                ans = a
                
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate


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

    seen = set()
    loop_list = []
    for start in range(n):
        v = start
        loop = []
        while v not in seen:
            seen.add(v)
            loop.append(c[v])
            v = p[v]
        seen.add(v)
        if loop:
            loop_list.append(loop)

    ans = min(c)
    for loop in loop_list:
        loop_len = len(loop)
        loop_num = k // loop_len
        loop_mod = k % loop_len
        loop_sum = sum(loop)
        table = [list(accumulate(loop[i:] + loop[:i])) for i in range(loop_len)]
        ans = max(max(max(table[i][:min(loop_len, k)]) for i in range(loop_len)), ans)
        if loop_num > 0:
            ans = max(loop_sum * (loop_num - 1) + max(max(table[i][:loop_len]) for i in range(loop_len)), ans)
            if loop_mod > 0:
                ans = max(loop_sum * loop_num + max(max(table[i][:loop_mod]) for i in range(loop_len)), ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

to_do = []
res = -float('inf')
for i in range(1,n+1):
    tmp_idx = i
    tmp_val = 0
    tmp_dic = {i:(0,0,i)}
    for j in range(1,min(n+1,k+1)):
        tmp_idx = ps[tmp_idx-1]
        tmp_val += cs[tmp_idx-1]
        res = max(res,tmp_val)
        if tmp_idx not in tmp_dic:
            tmp_dic[tmp_idx] = (j,tmp_val,tmp_idx)
        else:
            if tmp_val > tmp_dic[tmp_idx][1]:
                to_do.append([i,tmp_dic[tmp_idx][0],tmp_dic[tmp_idx][2],tmp_dic[tmp_idx][1],j-tmp_dic[tmp_idx][0],tmp_val-tmp_dic[tmp_idx][1]])
            break

for do in to_do:
    itr = (k - do[1]) // do[4]
    if itr > 0:
        itr -= 1
    remain = k - do[1] - do[4] * itr
    tmp_res = do[3] + itr * do[5]
    res = max(res,tmp_res)
    now = do[2]
    for i in range(remain):
        now = ps[now-1]
        tmp_res += cs[now-1]
        res = max(res, tmp_res)
print(res)

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int,input().split(" "))
ar = list(map(int,input().split(" ")))
br = list(map(int,input().split(" ")))
mx = -(10 ** 10)
for i in range(n):
    c = 0
    s = 0
    j = ar[i] - 1
    while True:
        if c == k:
            break 
        s += br[j]
        j = ar[j] - 1
        c += 1
        if mx < s:
            mx = s 
print(mx)

Submission status: Time Limit Exceeded

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

ans = -10**9
for i in range(n):
    d = []
    d_sum = 0
    pi = p[i]
    cnt = 0
    d_max = -10**9
    while pi != p[i] or cnt == 0 or k <= cnt:
        d_sum += c[pi-1]
        d_max = max(d_max, d_sum)
        d.append(d_sum)
        pi = p[pi-1]
        cnt += 1
    # print(d)
    # print(d_max)
    if k <= cnt:
        d_ans = d_max
    else:
        rp = k//cnt
        mod = k%cnt
        if mod == 0:
            d_tmp = d[-1]*rp+d_max
        else:
            d_tmp = max(d[-1]*rp+max(d[:mod]), d[-1]*(rp-1)+max(d[mod:]))
        d_ans = max(d_tmp, d_max)
    ans = max(ans, d_ans)
print(ans)

Submission status: Time Limit Exceeded

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

for i in range(N):
    p = i+1
    point = 0
    for j in range(K):
        p = P[p-1]
        point += C[p-1]
        if i == 0 and j == 0:
            ans = point
        elif ans < point:
            ans = point

print(ans)

Submission status: Time Limit Exceeded

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**20 * -1
for si in range(N):
    x = si
    s = []
    tot = 0
    while True:
        x = P[x]
        s.append(C[x])
        tot += C[x]
        if x == si:
            break
    l = len(s)
    t = 0
    for i in range(l):
        t += s[i]
        if i+1 > K:
            break

        now = t
        if tot > 0:
            e = (K - (i + 1)) // l
            now += tot * e
        ans = max(ans, now)
print(ans)