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:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import glob

class InputGenerator(object):
    def __init__(self, input_path=None):
        if input_path != None:
            self.g = self.input_generator(input_path)
        else:
            self.g = None

    def input_generator(self, input_path):
        with open(input_path) as f:
            for line in f:
                yield line

    def get_input(self):
        if self.g == None:
            return input()
        else:
            return next(self.g)

def get_max_local_trip(sorted_c_list, local_trip_k):
    n = len(sorted_c_list)
    local_trip_sum_max = -1e10
    sorted_c_list += sorted_c_list
    for i in range(0, 2*n):
        for j in range(i, 2*n):
            local_trip = sorted_c_list[i:j+1]
            if len(local_trip) <= local_trip_k:
                local_trip_sum = sum(local_trip)
                # print(i, j, local_trip, len(local_trip), local_trip_sum)
                if local_trip_sum > local_trip_sum_max:
                    local_trip_sum_max = local_trip_sum

    return local_trip_sum_max

def get_local_kn(sorted_c_list, k):
    n = len(sorted_c_list)

    if k % n == 0:
        num_round    = k // n - 1
        local_trip_k = n
    else:
        num_round    = k // n
        local_trip_k = k % n
        # print(num_round, local_trip_k)

    return num_round, local_trip_k

def get_local_max_score(sorted_c_list, k):
    num_round, local_trip_k = get_local_kn(sorted_c_list, k)

    round_sum = sum(sorted_c_list)
    local_max_score = get_max_local_trip(sorted_c_list, local_trip_k)
    # print('max', local_max_score, round_sum, num_round, local_trip_k)

    if round_sum > 0 and num_round > 0:
        local_max_score += (num_round * round_sum)

    return local_max_score

def solve(gen):
    n, k = list(map(int, gen.get_input().rstrip().split()))
    p_list = list(map(int, gen.get_input().rstrip().split()))
    c_list = list(map(int, gen.get_input().rstrip().split()))
    # print(n, k)
    # print(p_list)
    # print(c_list)

    sorted_c_list = []
    global_max_score = -1e10
    unvisited_list = list(range(n))
    for i in unvisited_list:
        start_i = i
        while True:
            next_i = p_list[i] - 1
            sorted_c_list.append(c_list[next_i])
            i = next_i
            if i == start_i:
                local_max_score = get_local_max_score(sorted_c_list, k)
                if global_max_score < local_max_score:
                    global_max_score = local_max_score
                sorted_c_list = []
                break
            else:
                unvisited_list.remove(i)

    print(global_max_score)

if __name__ == '__main__':
    test_flag = len(sys.argv) > 1

    if test_flag == True:
        file_path_list = sorted(glob.glob('test/*'))
    else:
        file_path_list = [None]

    for file_path in file_path_list:
        gen = InputGenerator(file_path)
        solve(gen)

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 = min(C)
for i in range(N) :
    log = [i+1]
    t = 0
    b = 0
    a = i+1
    while len(log) == len(set(log)) :
        b += C[P[a-1]-1]
        ans = max(ans,b)
        t += 1
        log.append(P[a-1])
        a = P[a-1]
        if t == K :
            break
    if b >= 1  :
       d = K%t
       e = K//t
       f = b*e
       for _ in range(d) :
           f += C[P[a-1]-1]
           a = P[a-1]
       ans = max(ans,f)
 
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):
    pos = i
    score = 0
    for k in range(K):
        pos = P[pos] - 1
        score += C[pos]
        if i == 0 and k == 0:
            ans = score
        else:
            ans = max(ans, score)

print(ans)
# print(N, K, P, C)

Submission status: Time Limit Exceeded

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

pList = list(map(int,input().split()))

cList = list(map(int,input().split()))

cSum = sum(cList)
p = dict()
c = dict()

for i in range(n):
    p[i] = pList[i]
    c[i] = cList[i]

highScore = min(cList)
for i in range(n):
    count = 0
    zahyou = i
    score = 0
    zumi =set()
    loop = False
    while count < k:
        if not(loop):
            if zahyou in zumi:
                loop = True
                if score > 0:
                    score += score * ((k // count) - 2)
                    count += ((k // count) - 2) * count
                else:
                    break
        zumi.add(zahyou)
        zahyou = p[zahyou] - 1
        score += c[zahyou]
        count += 1
        if highScore < score:
            highScore = score

print(highScore)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N, K = [int(x) for x in input().split()]
    P = [int(x) for x in input().split()]
    C = [int(x) for x in input().split()]

    ans = -float("inf")
    for i in range(N):
        next = P[i] - 1
        visited = set()
        cnt = 0
        tmp = 0
        f = False
        while next not in visited:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == K:
                f = True
                break
            visited.add(next)
            next = P[next] - 1

        if f or cnt <= 0:
            continue

        q, r = divmod(K, cnt)
        tmp *= q
        cnt = 0
        while True:
            tmp += C[next]
            ans = max(ans, tmp)
            cnt += 1
            if cnt == r:
                break
            next = P[next] - 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

pList = list(map(int,input().split()))

cList = list(map(int,input().split()))

cSum = sum(cList)
p = {}
c = {}

for i in range(n):
    p[i] = pList[i]
    c[i] = cList[i]

highScore = min(cList)
for i in range(n):
    count = 0
    zahyou = i
    score = 0
    zumi =set()
    loop = False
    while count < k:
        if not(loop):
            if zahyou in zumi:
                loop = True
                if score > 0:
                    score += score * ((k // count) - 2)
                    count += ((k // count) - 2) * count
                else:
                    break
        zumi.add(zahyou)
        zahyou = p[zahyou] - 1
        score += c[zahyou]
        count += 1
        if highScore < score:
            highScore = score

print(highScore)

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

l = [[] for i in range(n)]

for i in range(n):
    plc = i
    for j in range(k):
#        logging.debug(plc-1)
        l[i].append(c[p[plc]-1])
        plc = p[plc]-1

#logging.debug(l)

ans = -(10 ** 10)
for i in range(n):
    for j in range(len(l[i])):
        nw = sum(l[i][:j+1])
#        logging.debug(nw)
        if  nw > ans:
            ans = nw
#        logging.debug("ans = {} ".format(ans))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
 
def solve(N, K, P, C):
    ans = -10**18
    for start in range(N):
        t = 1
        s = 0
        idx = start
        while P[idx] != start:
            idx = P[idx]
            s += C[idx]
            t += 1
        s += C[start]
        q = K // t
        score = 0
        if s >= 0:
            x = max(0, (q-2)*t)
            score += s * (x//t)
            idx = start
            for _ in range(x, K):
                idx = P[idx]
                score += C[idx]
                ans = max(ans, score)
        else:
            idx = start
            for _ in range(1, min(N, K+1)):
                idx = P[idx]
                score += C[idx]
                ans = max(ans, score)
    return ans
 
def main():
    N, K = map(int, input().split())
    P = np.array(input().split(), dtype=np.int64)-1
    C = np.array(input().split(), dtype=np.int64)
    ans = solve(N, K, P, C)
    print(ans)
 
main()

Submission status: Time Limit Exceeded

Solution code:
def read_input():

    n, k = map(int, input().split())
    p = list(map(lambda x : int(x) - 1, input().split()))
    c = list(map(int, input().split()))

    return n, k, p, c

def solve_i(i, k, p, c, n):
    
    points = None
    maxi = None

    s = set()
    i = p[i]
    while i not in s:
        
        if points is None:
            points = [c[i]]
        else:
            points.append(points[-1] + c[i])

        if maxi is None:
            maxi = points[-1]
        else:
            maxi = max(maxi, points[-1])

        i = p[i]

    if points[-1] <= 0:
        return maxi
    else:
        cycles = k // n

        potential = points[-1] * cycles + max(points)

        return max(maxi, potential)



def solve(n, k, p, c):

    maxi = []
    for i in range(n):
        maxi.append(solve_i(i, k, p, c, n))

    return max(maxi)        


print(solve(*read_input()))

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

def solve():
    N, K = map(int, input().split())
    Ps = list(map(lambda x: int(x)-1, input().split()))
    Cs = list(map(int, input().split()))

    cycless = [[] for _ in range(N)]
    useds = [0] * N
    for no in range(N):
        if useds[no]: continue
        x = no
        while True:
            useds[x] = 1
            cycless[no].append(Cs[x])
            x = Ps[x]
            if x == no:
                break

#    for no in range(N):
#        print('# no:', no, '/ cycless[no]:', cycless[no], file=sys.stderr)

    ans = -float('inf')
    for no in range(N):
        if not cycless[no]: continue
        L = len(cycless[no])
        accCycles = list(accumulate([0]+cycless[no]+cycless[no]+cycless[no]))
        sumC = sum(cycless[no])
#        print('\n# no:', no, '/ sumC:', sumC, file=sys.stderr)
        if sumC > 0:
            num = K//L
            if num > 1:
                num -= 1
                score = -float('inf')
#                print('# K:', K, file=sys.stderr)
                for M in range(0, L + K%L+1):
                    for st in range(L):
                        s = accCycles[st+M] - accCycles[st]
                        if s > score:
                            score = s
                score += sumC * num
            else:
                score = -float('inf')
                for M in range(1, K+1):
                    for st in range(L):
                        s = accCycles[st+M] - accCycles[st]
                        if s > score:
                            score = s
        elif sumC == 0:
            num = K//L
            if num > 1:
                score = -float('inf')
                for M in range(0, 2*L+1):
                    for st in range(L):
                        s = accCycles[st+M] - accCycles[st]
                        if s > score:
                            score = s
            else:
                score = -float('inf')
                for M in range(1, K+1):
                    for st in range(L):
                        s = accCycles[st+M] - accCycles[st]
                        if s > score:
                            score = s
        else:
            score = -float('inf')
            for M in range(1, (K if K <= L else L)+1):
                for st in range(L):
                    s = accCycles[st+M] - accCycles[st]
                    if s > score:
                        score = s
        if score > ans:
            ans = score
#        print('# no:', no, '/ score:', score, file=sys.stderr)

    print(ans)


solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def main(K, P, C):
    N = len(P)
    INF = 1 << 60
    P = P - 1
    best_score = -INF
    for v in range(N):
        w = v
        L = 0
        S = 0
        while True:
            S += C[w]
            L += 1
            w = P[w]
            if v == w:
                break
        score = 0
        w = v
        for n in range(1, L + 1):
            score += C[w]
            w = P[w]
            if n > K:
                break
            max_add = (K - n) // L
            x = score + max(S * 0, S * max_add)
            best_score = max(best_score, x)
    return best_score
 
N, K = map(int, readline().split())
P = np.array(readline().split(), np.int64)
C = np.array(readline().split(), np.int64)
 
print(main(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()))
m = C[0]
for i in range(N):
  p = i
  s = 0
  for j in range(K):
    if p == i:
      if s < 0:
        break
    p = P[p]-1
    s = s + C[p]
    if s > m:
      m = s
print(m)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from itertools import accumulate

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
INF = 10**18
ans = - INF
used = [0] * N
candidate = []

for i in range(N):
    if used[i]: continue
    now = i
    used[i] = 1
    tmp = [i]
    
    while P[now]-1 not in tmp:
        used[P[now]-1] = 1
        tmp.append(P[now]-1)
        now = P[now]-1

    candidate.append(tmp)

for tmp in candidate:
    M = len(tmp)
    accumT = []
    for t in tmp:
        accumT.append(C[t])
    loop = 3
    accumT = [0] + list(accumulate(accumT*loop))
    res = - INF

    if K <= M:
        for i in range(loop*M+1):
            for j in range(i+1,loop*M+1):
                if j-i > K:
                    break
                res = max(res,accumT[j]-accumT[i])
        ans = max(ans,res)
    else:
        SUM = accumT[M]
        if SUM > 0:
            addition = SUM * (K//M - 1)# K//M回回らない方がいい場合がある
            for i in range(loop*M+1):
                for j in range(i+1,loop*M+1):
                    if j-i > K%M+M:
                        break
                    res = max(res,accumT[j]-accumT[i])
            ans = max(ans,res+addition)
        else:
            for i in range(loop*M+1):
                for j in range(i+1,loop*M+1):
                    if j-i > M:
                        break
                    res = max(res,accumT[j]-accumT[i])
            ans = max(ans,res)
print(ans)

Submission status: Time Limit Exceeded

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 for i in range(N+1)]
        # 1周の長さ
        size = 0
        # 1周のスコアの最大値: D[size]
        j = i
        score = 0
        while True:
            size += 1
            j = P[j]
            D[size] = D[size-1] + C[P[j]]
            if i == j:
                break
        round_score = D[size]
        for i in range(1, min(K, size)+1):
            max_score = max(max_score, D[i])
        # 周回してみる
        if D[size] > 0 and K > size:
            base_score = round_score * ((K // size)-1)
            max_score = max(max_score, base_score)
            for i in range(1, size+1):
                max_score = max(max_score, base_score + D[i])
            base_score = round_score * (K // size)
            for i in range(1, min(K%size, size)+1):
                max_score = max(max_score, base_score + D[i])
    return max_score


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

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()))
maximum = -10**9
for i in range(n):
    totalfull = 0; totalcut = 0; count = 0; location = i
    maximumfull = -10**9; maximumcut = -10**9
    for j in range(min(n, k)):
        location = p[location]-1
        totalfull += c[location]
        maximumfull = max(maximumfull, totalfull)
        count += 1
        if location == i: break
    for j in range(k%count):
        location = p[location]-1
        totalcut += c[location]
        maximumcut = max(maximumcut, totalcut)
    maximum = max(maximum, max(maximumfull, max((k//count-1)*totalfull+maximumfull, k//count*totalfull+maximumcut)))
print(maximum)

Submission status: Time Limit Exceeded

Solution code:
def solve(n,x,k):
  ans=-10**20
  s=0
  sx=sum(x)
  for i in range(n):
    if (i+1)>k:break
    s+=x[i]
    d=((k-i-1)//n)*sx
    ans=max(ans,s+d,s)
  return ans

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
for i in range(n):
  x=[c[i]]
  j=p[i]
  while i!=j:
    x.append(c[j])
    j=p[j]
  x=x[1:]+[x[0]]
  ans=max(ans,solve(len(x),x,k))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import glob

class InputGenerator(object):
    def __init__(self, input_path=None):
        if input_path != None:
            self.g = self.input_generator(input_path)
        else:
            self.g = None

    def input_generator(self, input_path):
        with open(input_path) as f:
            for line in f:
                yield line

    def get_input(self):
        if self.g == None:
            return input()
        else:
            return next(self.g)

def get_max_local_trip(sorted_c_list, local_trip_k):
    n = len(sorted_c_list)
    local_trip_sum_max = -1e10
    sorted_c_list += sorted_c_list
    for i in range(0, 2*n):
        for j in range(i, 2*n):
            local_trip = sorted_c_list[i:j+1]
            if len(local_trip) <= local_trip_k:
                local_trip_sum = sum(local_trip)
                # print(i, j, local_trip, len(local_trip), local_trip_sum)
                if local_trip_sum > local_trip_sum_max:
                    local_trip_sum_max = local_trip_sum

    return local_trip_sum_max

def get_local_kn(sorted_c_list, k):
    n = len(sorted_c_list)

    if k % n == 0:
        num_round    = k // n - 1
        local_trip_k = n
    else:
        num_round    = k // n
        local_trip_k = k % n
        # print(num_round, local_trip_k)

    return num_round, local_trip_k

def solve(gen):
    n, k = list(map(int, gen.get_input().rstrip().split()))
    p_list = list(map(int, gen.get_input().rstrip().split()))
    c_list = list(map(int, gen.get_input().rstrip().split()))
    # print(n, k)
    # print(p_list)
    # print(c_list)

    sorted_c_list = []
    sorted_c_list_list = []

    unvisited_list = list(range(n))
    for i in unvisited_list:
        start_i = i
        while True:
            next_i = p_list[i] - 1
            sorted_c_list.append(c_list[next_i])
            i = next_i
            if i == start_i:
                # print(sorted_c_list)
                sorted_c_list_list.append(sorted_c_list)
                sorted_c_list = []
                break
            else:
                unvisited_list.remove(i)

    global_max_score = -1e10
    for sorted_c_list in sorted_c_list_list:
        num_round, local_trip_k = get_local_kn(sorted_c_list, k)

        round_sum = sum(sorted_c_list)
        local_max_score = get_max_local_trip(sorted_c_list, local_trip_k)
        # print('max', local_max_score, round_sum, num_round, local_trip_k)

        if round_sum > 0 and num_round > 0:
            local_max_score += (num_round * round_sum)

        if global_max_score < local_max_score:
            global_max_score = local_max_score

    print(global_max_score)

if __name__ == '__main__':
    test_flag = len(sys.argv) > 1

    if test_flag == True:
        file_path_list = sorted(glob.glob('test/*'))
    else:
        file_path_list = [None]

    for file_path in file_path_list:
        gen = InputGenerator(file_path)
        solve(gen)

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

score = []

ans = -10**10
ans2 = -10**20
for i in range(N):
    ans_ = 0
    now = i
    score = []
    next = P[now] - 1
    for p in range(K):
        ans_ += C[next]
        ans = max(ans, ans_)
        now = next
        next = P[now] - 1
        score.append(ans_)
        if len(score) == (K % N):
            ans2 = max(ans2, sum(score))
            del(score[0])
        

if K <= N:
    print(ans)
else:
    a = ans * (K // N)
    if a > ans2:
        print(a + ans2)
    else:
        print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
read = sys.stdin.buffer.read
sys.setrecursionlimit(10 ** 7)
INF = float('inf')

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

LIM = - (10 ** 9 + 1)

ans = LIM
for i in range(N):
    res = [0] * (N + 1)
    seen = [0] * N
    k = 0
    pos = i
    while True:
        if seen[pos]:
            break
        if k >= K:
            break
        seen[pos] = 1
        pos = P[pos] - 1
        k += 1
        # print("k: {} pos: {}".format(k, pos))
        res[k] = res[k-1] + C[pos]
        ans = max(ans, res[k])
    # print("i: {} k: {} res: {}".format(i, k, res))

    if k < K:
        # kのループが存在する
        if res[k] > 0:
            q, mod = divmod(K, k)
            tmp_ans = (res[k] * q) + res[mod]
            ans = max(ans, tmp_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()))

# N: マスの数
# K: 移動回数の上限
# P: 1〜Nがランダムに並んでる
# C: マスに書かれている整数

squares = []
for i in range(N):
    squares.append((P[i] - 1, C[i]))

# 最初のマスを全探索
max_score = 0
for i in range(N):
    current = squares[i]
    move_count = 1 # 最低1回は移動させる必要がある
    high_score = 0

    while move_count <= K:
        score = 0
        for _ in range(move_count):
            # 移動する
            current = squares[current[0]]
            score += current[1]
        if high_score < score:
            high_score = score
        move_count += 1

    if max_score < high_score:
        max_score = high_score

if max_score == 0:
    max_score = max(C)

print(max_score)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
from queue import deque
readline = sys.stdin.buffer.readline
from collections import Counter
#sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


import numpy as np


def main():
    n, k = geta(int)
    p = [0] + list(geta(int))
    c = [0] + list(geta(int))

    inf = 1 << 32

    used = [False] * (n + 1)

    ans = -inf

    for i in range(1, n + 1):

        if used[i]:
            continue
        else:
            used[i] = True

        c_loop = []
        j = p[i]
        c_loop += [c[j]]

        while j != i:
            used[j] = True
            j = p[j]
            c_loop += [c[j]]

        n_loop = len(c_loop)
        c_loop = np.array(c_loop + c_loop)
        cs_loop = np.cumsum(c_loop)
        tot_loop = cs_loop[n_loop - 1]

        _jmax = k if k < n_loop else n_loop

        _ans = -inf
        _len = 0
        for _i in range(n_loop):
            for _j in range(1, _jmax + 1):
                _tmp = cs_loop[_j + _i] - cs_loop[_i]

                if tot_loop > 0 and k > _j:
                    _tmp += (k - _j) // n_loop * tot_loop

                if _ans < _tmp:
                    _ans = _tmp

        if ans < _ans:
            ans = _ans

    print(ans)


if __name__ == "__main__":
    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()))

for i in range(N):
  P[i] -= 1

ans = max(C)
S = set(range(N))
while S:
  scores = []
  x = S.pop()
  while True:
    scores.append(C[x])
    x = P[x]
    if x not in S:
      break
    S.remove(x)
  l = len(scores)
  if K <= l:
    for i in range(l):
      if scores[i] <= 0:
        continue
      ss = 0
      for k in range(K):
        ss += scores[(i+k)%l]
        ans = max(ans, ss)
  else:
    t = sum(scores)
    t = t * (K // l - 1) if t > 0 else 0
    for i in range(l):
      if scores[i] <= 0:
        continue
      ss = t
      for k in range(l + (K%l)):
        ss += scores[(i+k)%l]
        ans = max(ans, ss)

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


maxx=c[0]
for i in range(n):
    ind=i
    val=0
    for move in range(k):
        ind=p[ind]-1
        val+=c[ind]
        maxx=max(val,maxx)
print(maxx)

Submission status: Time Limit Exceeded

Solution code:
(n, k), p, c = [[*map(int, i.split())] for i in open(0)]
visit = [0] * n
visit[0] = 1
loop = [0] * n
count = a = 0
while True:
    a = p[a] - 1
    if visit[a]:
        if loop[a]:
            break
        count += c[a]
        loop[a] = 1
    visit[a] = 1

ln = sum(loop)


def solve(x, t):
    ans = c[p[x] - 1]
    l = True
    sub = 0
    while True:
        if loop[x] and l:
            if t > ln:
                if count >0:
                    sub += (t // ln - 1) * count
                t %=ln
                t += ln
            l = False
        if t < 1:
            ans = max(sub, ans)
            return ans
        x = p[x] - 1
        sub += c[x]
        t -= 1
        ans = max(sub, ans)


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

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()))
score = -1000000000000
for i in range(n):
    p = i+1
    s = 0
    for j in range(k):
        p = P[p-1]
        s += C[p-1]
        if s > score:
            score = s
print(score)

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
def solve(P, C, K, Checked, s):
    B = []
    B.append( C[s])
    now = P[s]
    Checked[s] = True
    while now != s:
        B.append(C[now])
        Checked[now] = True
        now = P[now]
    sumB = sum(B)
    L = len(B)
    accB = [0] + list( accumulate(B))
    ret = B[0]
    for i in range(L):
        for j in range(i+1,L+1):
            if j - i > K:
                continue
            if accB[j] - accB[i] > ret:
                ret = accB[j] - accB[i]
    accRB = [0] + list( accumulate(B[::-1]))
    # print(B, accB, accRB)
    # print(ret)
    for i in range(L+1):
        for j in range(L+1):
            if i==0 and j==0:
                continue
            if i + j > K:
                continue
            t = accB[i] + accRB[j]
            if sumB > 0:
                t += (K-(i+j))//L*sumB
            if t > ret:
                ret = t
                # print(i,j,ret)
    return ret
        
    
def main():
    N, K = map( int, input().split())
    P = list( map( lambda x: int(x)-1, input().split()))
    C = list( map( int, input().split()))
    Checked = [False]*N
    ans = C[0]
    for s in range(N):
        if Checked[s]:
            continue
        ans_s = solve(P, C, K, Checked, s)
        if ans_s > ans:
            ans = ans_s
    print(ans)
if __name__ == '__main__':
    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()))


hscore = -999
fscore = -999
for st in range(len(P)):
    score = 0
    first = True
    for _ in range(K):
        if first:
            nxt = P[st]-1
            first = False
        else:
            nxt = P[nxt]-1
        score += C[nxt]
        if fscore == -999 or fscore<score:
            fscore = score
        if hscore<score:
            hscore = score

if hscore == -999:
    print(fscore)
else:
    print(hscore)