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:
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))
        score += max(cycle_score_cum)

        ans = max(score, ans)

    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

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

visited = [False] * N
ans = []
for i in range(N):
    if visited[i]:
        continue
    visited[i] = True
    S = [C[i]]
    p = P[i]
    while p != i:
        visited[p] = True
        S.append(C[p])
        p = P[p]
    s = sum(S)
    n = len(S)
    SS = S + S
    if s <= 0 or K <= n:
        a = max(sum(SS[j:j + c + 1])
                for j in range(n) for c in range(min(K, n)))
    else:
        M = max(sum(SS[j:j + c + 1]) for j in range(n) for c in range(K % n))
        a = s * (K // n) + M
    ans.append(a)

print(max(ans))

Submission status: Runtime Error

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

visited = [False] * N
ans = []
for i in range(N):
    if visited[i]:
        continue
    visited[i] = True
    S = [C[i]]
    p = P[i]
    while p != i:
        visited[p] = True
        S.append(C[p])
        p = P[p]
    s = sum(S)
    n = len(S)
    SS = S + S
    if s <= 0 or K < n:
        a = max(sum(SS[j:j + c + 1])
                for j in range(n) for c in range(min(K, n)))
    else:
        M = max(sum(SS[j:j + c + 1]) for j in range(n) for c in range(K % n))
        a = s * (K // n) + M
    ans.append(a)

print(max(ans))

Submission status: Runtime Error

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

visited = [False] * N
ans = []
for i in range(N):
    if visited[i]:
        continue
    visited[i] = True
    S = [C[i]]
    p = P[i]
    while p != i:
        visited[p] = True
        S.append(C[p])
        p = P[p]
    s = sum(S)
    n = len(S)
    SS = S + S
    if s <= 0 or K < n:
        a = max(sum(SS[j:j + c + 1])
                for j in range(N) for c in range(min(K, n)))
    else:
        M = max(sum(SS[j:j + c + 1]) for j in range(N) for c in range(K % n))
        a = s * (K // n) + M
    ans.append(a)

print(max(ans))

Submission status: Runtime Error

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

max_score = min(c)
for init_mass in range(n):
    curr_mass = p[init_mass]
    scores = [c[init_mass]]
    while curr_mass != init_mass:
        scores.append(scores[-1] + c[curr_mass])
        curr_mass = p[curr_mass]
    cycle_score = scores[-1]

    if len(scores) >= k:
        score = max(scores[:k])
    elif cycle_score <= 0:
        score = max(scores)
    else:
        cycle_len = len(scores)
        max_cycle_num, cycle_rem = divmod(k, cycle_len)
        score = max(cycle_score * (max_cycle_num - 1) + max(scores),
                    cycle_score * max_cycle_num + max(scores[:cycle_rem]))

    if score > max_score:
        max_score = score

print(max_score)

Submission status: Runtime Error

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

def main():
  n, k = map(int, input().strip().split())
  lp = list(map(lambda c:int(c)-1, input().strip().split()))
  lc = list(map(int, input().strip().split()))
  used = [0] * n
  loops = []
  for i in range(n):
    if used[i] == 1:
      continue
      
    ic = i
    loop = []
    while True:
      loop.append(lc[ic])
      used[ic] = 1      
      ic = lp[ic]
      if used[ic] == 1:
        break
    if len(loop) > 0:
      loops.append(loop)
    
    
  def f(loop, k):
    if max(loop) < 0:
      return max(loop)
    
    score = 0
    if sum(loop) > 0:
      score += (k // len(loop)) * sum(loop)
      k = k % len(loop)
    k = min(k, len(loop)-1)
    loop = 2 * loop
    score += max([sum(loop[i:i+ik]) for i in range(len(loop)//2) for ik in range(1, k+1)])
    return score
  
  print(max([f(loop, k) for loop in loops]))

if __name__=='__main__':
  main()

Submission status: Runtime Error

Solution code:
n, k = [int(i) for i in input().split(' ')]
number = [int(i) for i in input().split(' ')]
point = [int(i) for i in input().split(' ')]
res = []


for i in range(n) :
  i += 1
  cnt = 1
  num = number[i-1]
  loop = []
  tmp = 0
  while i != num :
    tmp += point[num-1]
    loop.append(tmp)
    num = number[num-1] 
    cnt += 1
  tmp += point[i-1]
  loop.append(tmp)
  if k >= cnt :
    if tmp >= 0 :
      loopcnt = k // cnt
      amari = k % cnt
      result = tmp*loopcnt + max(loop[0:amari])
    else :
      result = max(loop)
  else :
      result = max(loop[0:k])
  res.append(result)
print(max(res))

Submission status: Runtime Error

Solution code:
x, k, d = [int(i) for i in input().split()]
for i in range(k):
  if abs(x - d) >= abs(x + d):
    x += d
  else:
    x -= d
print(abs(x))

Submission status: Runtime Error

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

score = []
ans = -10 ** 10
o = n // k
p = n % k

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

if k > n and sum(c) > 0:
    for l in range(n):
        b = p[l] - 1
        for m in range(p):
            score[l] = sum(c) * o
            score[l] += c[b]
            b = p[b] - 1
            if score[l] > ans:
                ans = score[l]
    for q in range(n):
        d = p[q] - 1
        for r in range(n):
            score[q] = sum(c) * (o - 1)
            score[q] += c[d]
            d = p[d] - 1
            if score[q] > ans:
                ans = score[q]

print(ans)

Submission status: Runtime Error

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

x, k, d = map(int, input().split())
r = x%d
q = int(x/d)
if k&1:
	if r < d-r:
		if q&1: print(r)
		else: print(d-r)
	else:
		if q&1: print(d-r)
		else: print(r)
else:
	if r < d-r:
		if q&1: print(d-r)
		else: print(r)
	else:
		if q&1: print(r)
		else: print(d-r)

Submission status: Runtime Error

Solution code:
import sys; input = sys.stdin.readline
from math import ceil

x, k, d = map(int, input().split())
r = x%d
q = x//d
if k&1:
	if r < d-r:
		if q&1: print(r)
		else: print(d-r)
	else:
		if q&1: print(d-r)
		else: print(r)
else:
	if r < d-r:
		if q&1: print(d-r)
		else: print(r)
	else:
		if q&1: print(r)
		else: print(d-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()))
dic = {}
for i in range(1, n+1):
  dic[i] = [p[i-1], c[i-1]]
INF = 10**20
ans = -INF
for j in range(1, n+1):
  state = [True] * 5001
  max_score = -INF
  max_idx = 0
  score = 0
  now = dic[j][0]
  cnt = 0
  lst = []
  flg = True
  for _ in range(k):
    if not state[now]:
      flg = False
      break
    score += dic[now][1]
    cnt += 1
    if max_score < score:
      max_score = score
      max_idx = cnt
    lst.append(score)
    state[now] = False
    now = dic[now][0]
  if score <= 0 or flg:
    ans = max(max_score, ans)
  else:
    q = k // cnt
    r = k % cnt
    if r >= max_idx:
      x = score * q + max_score
      ans = max(ans, x)
    else:
      if q >= 1:
        x = score * (q - 1) + max_score
        y = score * q + max(lst[:r])
        ans = max(ans, x, y)
      else:
        ans = max(ans, max_score)
print(ans)

Submission status: Runtime Error

Solution code:


def main():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    f_ans = -float('inf')

    for i in range(n):
        c_rev = []
        t_senni = []
        t = 0
        pi = p1 = p[i]

        c_rev.append(c[pi - 1])
        t += c[pi - 1]
        t_senni.append(t)
        pi = p[pi - 1]

        while pi != p1:
            c_rev.append(c[pi - 1])
            t += c[pi - 1]
            t_senni.append(t)
            pi = p[pi - 1]

        if t > 0:
            l = len(c_rev)
            pn = k % l
            c_rev_mod = c_rev[pn:l] + c_rev[0:pn]
            t_mod = 0
            mod = -float('inf')

            for j in range(l):
                t_mod += c_rev_mod[j]
                if mod < t_mod:
                    mod = t_mod

            ans = (k // l - 1) * t + t_senni[pn - 1] + mod

        else:
            if k >= l:
                ans = max(t_senni)
            else:
                ans = max(t_senni[0:k+1])

        if f_ans < ans:
            f_ans = ans

    print(f_ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
next_hop = list(map(int,input().split()))
point = list(map(int,input().split()))
#print(point)
dp = [[0]*(K) for _ in range(N)]
for i in range(N):
    dp[i][0] = point[next_hop[i]-1]

answer = [0 for _ in range(N)]
for i in range(N):
    a = next_hop[i] - 1
    a = next_hop[a]-1
    for j in range(1,K):
        dp[i][j] = dp[i][j-1] + point[a]
        a = next_hop[a] - 1
    answer[i] = max(dp[i])

print(max(answer))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
next_hop = list(map(int,input().split()))
point = list(map(int,input().split()))
#print(point)
dp = [[0]*(K+1) for _ in range(N)]
#print(dp)
answer = [0 for _ in range(N)]
for i in range(N):
    a = next_hop[i] - 1
    for j in range(1,K+1):
        dp[i][j] = dp[i][j-1] + point[a]
        a = next_hop[a] - 1
    answer[i] = max(dp[i])


print(max(answer))

Submission status: Runtime Error

Solution code:
// #define _GLIBCXX_DEBUG // for STL debug (optional)
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <fstream>
#include <functional>
#include <bitset>
using namespace std;
using ll = long long int;
using int64 = long long int;
 
template<typename T> void chmax(T &a, T b) {a = max(a, b);}
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chadd(T &a, T b) {a = a + b;}
 
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int INF = 1LL << 29;
const ll LONGINF = 1LL << 60;
const ll MOD = 1000000007LL;
 
int main() {
    int N, K; scanf("%d%d", &N, &K);
    vector<int> P(N);
    for(int i=0; i<N; i++) scanf("%d", &P[i]), P[i]--;
    vector<int> C(N);
    for(int i=0; i<N; i++) scanf("%d", &C[i]);

    ll ans = -LONGINF;
    vector<bool> visited(N);
    for(int i=0; i<N; i++) {
        if(visited[i]) continue;
        vector<int> cycle;
        int x = i;
        while(true) {
            visited[x] = true;
            cycle.emplace_back(C[x]);
            x = P[x];
            if(x == i) break;
        }

        int M = cycle.size();
        ll cost_w = accumulate(cycle.begin(), cycle.end(), 0LL);
        vector<ll> pref(M+1, -LONGINF);
        for(int i=0; i<M; i++) {
            ll sum = 0;
            for(int j=0; j<M; j++) {
                int p = (i+j)%M;
                sum += cycle[p];
                chmax(pref[j+1], sum);
            }
        }

        for(int k=1; k<M; k++) {
            int d = (K - k) / M;
            chmax(ans, max(0LL, cost_w * d) + pref[k]);
        }
    }
    cout << ans << endl;
    return 0;
}

Submission status: Runtime Error

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

# D - Moving Piece
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

# 問題文とインデックスの位置を揃える
P.insert(0, 0)
C.insert(0, 0)

# マス目を周期ごとに分割する
groups = []
appeared = set()

for i in range(1, N + 1):
	if not i in appeared:
		group = []
		s = set()
		j = i

		while not j in s:
			group.append(j)
			s.add(j)
			appeared.add(j)
			j = P[j]

		groups.append(group)

ans = -sys.maxsize

# 周期ごとにハイスコアを算出
for group in groups:
	# スタート位置を1マスずつズラす
	for g in group:
		score = 0
		max_score = -sys.maxsize
		scores = []
		scores.append(-sys.maxsize)
		Pi = P[g]

		for j in range(len(group)):
			score += C[Pi]
			max_score = max(max_score, score)
			scores.append(max_score)
			Pi = P[Pi]

		if K > N and score > 0:
			s = scores[K % len(group)] + score * (K // len(group))
			ans = max(ans, s)
		elif K > N:
			ans = max(ans, max_score)
		else:
			ans = max(ans, scores[K])

print(ans)

Submission status: Runtime Error

Solution code:
import sys

# D - Moving Piece
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

# 問題文とインデックスの位置を揃える
P.insert(0, 0)
C.insert(0, 0)

# マス目を周期ごとに分割する
groups = []
appeared = set()

for i in range(1, N + 1):
	if not i in appeared:
		group = []
		s = set()
		j = i

		while not j in s:
			group.append(j)
			s.add(j)
			appeared.add(j)
			j = P[j]

		groups.append(group)

ans = -sys.maxsize

# 周期ごとにハイスコアを算出
for group in groups:
	# スタート位置を1マスずつズラす
	for g in group:
		score = 0
		max_score = -sys.maxsize
		scores = []
		scores.append(-sys.maxsize)
		Pi = P[g]

		for j in range(len(group)):
			score += C[Pi]
			max_score = max(max_score, score)
			scores.append(max_score)
			Pi = P[Pi]

		if K > N and score > 0:
			s = scores[K % len(group)] + score * (K // len(group))
			ans = max(ans, s)
		elif K > N:
			ans = max(ans, max_score)
		else:
			ans = max(ans, scores[K])

print(ans)

Submission status: Runtime Error

Solution code:
#! /usr/bin/env python3
import itertools
import numpy as np
import fractions
from itertools import combinations
from functools import reduce
from functools import lru_cache
import math
from collections import deque
import decimal
import bisect
import heapq
import sys
sys.setrecursionlimit(10**9)


INF=10**20
def solve(N: int, K: int, P: "List[int]", C: "List[int]"):
    ans = -INF
    for i in range(N):
        start = i + 1 
        stack = [start]
        score_his = [0]
        scores = 0
        depth = 1
        seen = {}
        while stack:
            if depth > K: break
            current = stack.pop()
            
            if current in seen:
                loop_start_depth = seen[current]
                loop_end_depth = depth - 1 
                loop_scores = score_his[-1] - score_his[loop_start_depth-1]
                loop_len = loop_end_depth - loop_start_depth + 1
                if loop_scores < 0: break
 
                # print(start,score_his)
                # print(loop_start_depth,loop_end_depth,loop_scores,loop_len)
                
                rest_count = K - depth + 1
                available_loop_count = rest_count // loop_len
                res1 = (available_loop_count-1) * loop_scores + scores
 
                # print("a",rest_count,available_loop_count,res1)
                
                res2 = res1
                rest_loop_len = rest_count % loop_len + loop_len
 
                # print("b",rest_loop_len)
                ress = [res1,res2]
                for j in range(rest_loop_len):
                    score = C[P[current-1]-1]
                    res2 += score
                    ress.append(res2)
                    current = P[current-1]
 
                # print("ress",ress)
                score_his.append(max(ress))
 
                break
 
            
            score = C[P[current-1]-1]
            scores += score
            score_his.append(scores)
 
            seen[current] = depth
            stack.append(P[current-1])
 
            depth += 1
        
        ans = max(ans,max(score_his[1:]))
    
    print(ans)
 
 
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    C = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, K, P, C)



if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7


def debug(*x):
    print(*x, file=sys.stderr)


def solve0(N, K, PS, CS):
    PS = [x - 1 for x in PS]
    debug(": PS", PS)
    CS = [CS[PS[i]] for i in range(N)]
    PSS = [PS]
    CSS = [CS]
    prevPS = PS
    prevCS = CS
    for i in range(30):
        PS2 = [prevPS[prevPS[i]] for i in range(N)]
        CS2 = [prevCS[i] + prevCS[prevPS[i]] for i in range(N)]
        PSS.append(PS2)
        CSS.append(CS2)
        prevPS = PS2
        prevCS = CS2

    score = [0] * N
    pos = list(range(N))
    length = [0] * N
    maxbit = K.bit_length() - 1
    for i in range(maxbit, -1, -1):
        # debug(": i", i)
        # debug(": 2**i", 2**i)
        # debug(": CSS[i]", CSS[i])
        # debug(": PSS[i]", PSS[i])
        # debug(": score", score)
        # debug(": length", length)
        for j in range(N):
            # debug(": length[j] + 2 ** i <= K", length[j] + 2 ** i <= K)
            # debug(": CSS[i][pos[j]]", CSS[i][pos[j]])
            if length[j] + 2 ** i <= K and CSS[i][pos[j]] > 0:
                # debug("add: j", j)
                score[j] += CSS[i][pos[j]]
                pos[j] = PSS[i][pos[j]]
                length[j] += 2 ** i
            # if CSS[i][j] > score[j]:
            #     # debug("reset: j", j)
            #     # debug(": CSS[i][i], score[j]", CSS[i][i], score[j])
            #     pos[j] = PSS[i][j]
            #     score[j] = CSS[i][j]
            #     length[j] = 2 ** i

    # debug("finish: score", score)
    ret = max(score)
    if ret == 0:
        ret = max(CS)
    return ret


def solve(N, K, PS, CS):
    PS = [x - 1 for x in PS]
    CS = [CS[PS[i]] for i in range(N)]
    visited = {}
    loops = []
    loopScore = []
    for i in range(N):
        loop = []
        c = 0
        while i not in visited:
            visited[i] = True
            c += CS[i]
            i = PS[i]
            loop.append(i)
        if loop:
            loops.append(loop)
            loopScore.append(c)
    # debug(": loops", loops)
    # debug(": loopScore", loopScore)
    scores = [0] * N
    pos = list(range(N))
    from collections import defaultdict

    ret = 0
    for i, loop in enumerate(loops):
        if loopScore[i] > 0:
            baseScore = loopScore[i] * (K // len(loop))
            r = K % len(loop)
            if r == 0:
                r = len(loop)
                baseScore -= loopScore[i]
                # debug("r==0: baseScore", baseScore)
            maxscore = 0
            scores = defaultdict(int)
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                maxscore = max(maxscore, max(scores.values()))
                debug("posi: maxscores", scores)
            ret = max(maxscore + baseScore, ret)
        else:
            r = len(loop)
            maxscore = -INF
            scores = defaultdict(int)
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                debug("neg: scores", scores)
                maxscore = max(maxscore, max(scores.values()))
            ret = max(maxscore, ret)

    if ret == 0:
        ret = max(CS)
    return ret


def main():
    # parse input
    N, K = map(int, input().split())
    PS = list(map(int, input().split()))
    CS = list(map(int, input().split()))
    print(solve(N, K, PS, CS))


# tests
T1 = """
5 2
2 4 5 1 3
3 4 -10 -8 8
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
8
"""

T2 = """
2 3
2 1
10 -7
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
13
"""

T3 = """
3 3
3 1 2
-1000 -2000 -3000
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
-1000
"""

T4 = """
10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
29507023469
"""

T5 = """
3 1000
2 3 1
1 0 2
"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
1001
"""

T6 = """
3 1000
2 3 1
1 1 -3
"""
TEST_T6 = """
>>> as_input(T6)
>>> main()
2
"""

T7 = """
4 1000
2 1 4 3
1 1 -10000 10000
"""
TEST_T7 = """
>>> as_input(T7)
>>> main()
10000
"""

T8 = """
4 1000
2 1 4 3
1 1 -10000 10001
"""
TEST_T8 = """
>>> as_input(T8)
>>> main()
10001
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g, name=k)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

main()

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
score=-1000000000
res=[True for _  in range(n)]
res2=[]

for i in range(n):
    if res[i]:
        res[i]=False
        res2.append([])
        res2[-1].append(c[i])
        res3=p[i]-1
        while res3!=i:
            res[res3]=False
            res2[-1].append(c[res3])
            res3=p[res3]-1

res5=False

for i in range(len(res2)):
    l=len(res2[i])
    sum2=[0 for _ in range(l)]
    for j in range(l):
        res2[i].append(res2[i][j])
        res4=0
        count=0
        sum2[l-1]+=res2[i][j]
        for q in range(j,j+l):
            if res2[i][q]<=0:
                count=0
                res4=0
            else:
                res5=True
                count+=1
                res4+=res2[i][q]
                sum2[count-1]=max([res4,sum2[count-1]])
    s=max(sum2)
    if not res5:
        score=max([max(res2[i]),score])
        continue
    if l<k:
        s=max(s,sum2[l-1]*(k//l)+max(sum2[:k%l]))
    if s>score:
        score=s
        res5=True

print(score)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
score=-1000000000
res=[True for _  in range(n)]
res2=[]

for i in range(n):
    if res[i]:
        res[i]=False
        res2.append([])
        res2[-1].append(c[i])
        res3=p[i]-1
        while res3!=i:
            res[res3]=False
            res2[-1].append(c[res3])
            res3=p[res3]-1

sum=[0 for _ in range(len(res2))]
res5=False

for i in range(len(res2)):
    l=len(res2[i])
    sum2=[0 for _ in range(l)]
    for j in range(l):
        res2[i].append(res2[i][j])
    l2=len(res2[i])
    for j in range(l):
        res4=0
        count=0
        sum2[l-1]+=res2[i][j]
        for p in range(j,j+l):
            if res2[i][p]<=0:
                count=0
                res4=0
            else:
                res5=True
                count+=1
                res4+=res2[i][p]
                sum2[count-1]=max([res4,sum2[count-1]])
    s=max(sum2)
    if not res5:
        score=max([max(res2[i]),score])
        continue
    if l<k:
        s=max(s,sum2[l-1]*(k//l)+max(sum2[:k%l]))
    if s>score:
        score=s
        res5=True

print(score)

Submission status: Runtime Error

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

    ans = -100100100
    for i in range(N):
        node_set = set()
        n = P[i]
        score = 0
        t = []
        while n not in node_set:
            score += C[n-1]
            t.append(score)
            node_set.add(n)
            n = P[n-1]

        if K < len(t):
            max_t = max(t[:K])
        else:
            if t[-1] > 0:
                temp = t[-1] * int(K / len(t)) + max([0] + t[:K%len(t)])
                max_t = max(max_t, temp)
            else:
                max_t = max(t)
        ans = max(ans, max_t)

    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
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()]
 
def cycle_sum(A, K):
    L = len(A)
    S = set()
 
    for i in range(L):
        for j in range(L):
            if 1 <= j - i + 1 <= K:
                S.add(sum(A[i:j + 1]))
            elif j < i and 1 <= L - i + j + 1 <= K:
                S.add(sum(A[0:j + 1]) + sum(A[i:L]))
 
 
    return max(S)

def cycle_sup(A, K):
    L = len(A)
    S = sum(A)
    Q = K // L
    R = K % L

    if K <= L or S <= 0:
        return cycle_sum(A,K)
    else:
        return S * Q + cycle_sum(A, R)

def orb_decomp(P, C):
    N = len(P)
    S = set()
    D = []
 
    for i in range(1,N + 1):
        if i not in S:
            d = [C[i - 1]]
            o = [i]
            j = i
            j = P[j - 1]
            while j != i:
                d.append(C[j - 1])
                o = o + [j]
                j = P[j - 1]
            D.append(d)
            S = S | set(o)
    
    return D

D = orb_decomp(P, C)

M = max(cycle_sup(A, K) for A in D)
 
print(M)

Submission status: Runtime Error

Solution code:
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()]

def mysum(A, K):

    L = len(A)

    S = set()

    for i in range(L):
        for j in range(L):
            if 1 <= j - i + 1 <= K:
                S.add(sum(A[i:j + 1]))
            elif j < i and 1 <= L - i + j + 1 <= K:
                S.add(sum(A[0:j + 1]) + sum(A[i:L]))


    return max(S)

O = []
S = set()
o = []

for i in range(1,N + 1):
    if i not in S:
        o = [i]
        j = i
        j = P[j - 1]
        while j != i:
            o = o + [j]
            j = P[j - 1]
        O.append(o)
        S = S | set(o)

D = []
for o in O:
    d = []
    for i in o:
        d.append(C[i - 1])
    D.append(d)

candidates = set()

for d in D:
    if K <= len(d):
        candidates.add(mysum(d, K))
    else:
        if sum(d) > 0:
            candidates.add(sum(d) * (K // len(d)) + mysum(d, K % len(d)))
        else:
            candidates.add(mysum(d, len(d)))

print(max(candidates))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
p=[int(i) for i in input().split()]
c=[int(i) for i in input().split()]
score=[0]*n
for i in range(n):
    position=i
    s=[0]*k
    for j in range(k):
        position=p[position]-1
        if j==0:
            s[j]=c[position]
        else:
            s[j]=s[j-1]+c[position]
    score[i]=max(s)
print(max(score))