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 sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

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

ans = -float('inf')
for i in range(n):
    now = i
    c_sum = [0]
    s = set()
    cnt = 0
    while True:
        s.add(now)
        c_sum.append(c_sum[-1] + c[now])
        cnt += 1
        now = p[now]
        if now in s:
            break
    c_sum = c_sum[1:]
    if k < cnt:
        ans = max(ans, max(c_sum[: k]))
    else:
        score = c_sum[-1]
        count = k // cnt
        k_ = k - count*cnt
        score *= count
        if k_ > 0:
            score += max(c_sum[:k_], 0)
        ans = max(ans, score, max(c_sum))
print(ans)

Submission status: Runtime Error

Solution code:
import sys


def _ia(): return map(int, sys.stdin.readline().strip().split())


def calc(arr, k):
    s = sum(arr)
    n = len(arr)
    flag = s > 0 and k > n

    kp = k % n if flag else k
    l = min(kp, n)

    cm = max(arr) if s <= 0 else 0
    for i in range(n):
        cn = 0
        for ki in range(i, i+l):
            cn += arr[ki % n]
            cm = max(cn, cm)

    if flag:
        return s * (k//n) + cm
    else:
        return cm


def main():
    n, k = _ia()
    p = list(map(lambda x: x-1, _ia()))
    c = list(_ia())

    f = [False] * n
    g = []
    for idx in range(n):
        if f[idx]:
            continue

        nxt = idx
        tmp = [c[nxt]]
        f[nxt] = True

        for _ in range(n):
            nxt = p[nxt]
            if nxt == idx:
                break
            tmp.append(c[nxt])
            f[nxt] = True

        g.append(tmp)

    return calc(g[1], k)

    # return max(calc(gi, k) for gi in g)


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

ans = max(C)
for i in range(N):
    s = i
    while True:
        s = P[s]-1
        l.append(C[s])
        if s == i:
            break
    if sum(l) > 0:
        c = K//len(l)*sum(l)
        n = K%len(l)
        ans = max(ans,c)
        s = i
        x = 0
        for j in range(n):
            s = P[s]-1
            x += C[s]
            ans = max(ans,c+x)
    else:
        n = min(N,K)
        s = i
        x = 0
        for j in range(n):
            s = P[s]-1
            x += C[s]
            ans = max(ans,x)
            
print(ans)

Submission status: Runtime Error

Solution code:


def li():
    return [int(x) for x in input().split()]

N, K = li()
P = [0] + li()
C = [0] + li()
max_scores = [-10**12] * (N+10)
for init_i in range(1, N+1):
    i = init_i
    scores = [-10**9] * (K+10000)
    scores[0] = 0
    for l in range(1, K+1):
        i = P[i]
        scores[l] = scores[l-1] + C[i]
    scores[0] = -10**9
    max_scores[i] = max(scores)
print(max(max_scores))

Submission status: Runtime Error

Solution code:
import sys
N,K= map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
total=0
if sum(C)>0:
    n=int(K/N)
    total=total+sum(C)*n
    k=int(K-n*N)#kは高々N
else:
    total=0
    k=min(K,N)
count=0
max_1=[0]*k
max_2=[0]*N
for i in range(N):
    x=i#初期位置
    for j in range(k):
        x=P[x-1]#移動
        max_1[j]=max_1[j]+C[x-1]
    max_2[i]=max(max_1)
m=max(max_2)
print(total+m)

Submission status: Runtime Error

Solution code:
#include<iostream>
#include<vector>
#include<string>
#include<cmath>
using namespace std;

int main()
{
    long long int n, k, i, ans = -99999999999999, cost, temp, len, j;
    cin>>n>>k;
    vector<long long int> P(n+1);
    vector<long long int> C(n+1);
    for(i=1;i<=n;i+=1)
    {
        cin>>P[i];
    }
    for(i=1;i<=n;i+=1)
    {
        cin>>C[i];
    }
    for(i=1;i<=n;i+=1)
    {
        len = 0;
        temp = k-1;
        cost = C[i];
        j = i;
        ans = max(cost, ans);
        do
        {
            j = P[i];
            cost+=C[j];
            ans = max(ans, cost);
            temp-=1;
            len+=1;
        }
        while(j!=i and temp>0);
        if(temp>0)
        {
            temp = temp%len;
        }
      	cost = cost+cost*(temp/len);
        ans = max(ans, cost);
        j = i;
      	cost = cost+C[i];
      	ans = max(ans, cost);
      	temp-=1;
        while(temp>0)
        {
            j = P[i];
            cost+=C[j];
            ans = max(ans, cost);
            temp-=1;
        }
    }
    cout<<ans<<endl;
}

Submission status: Runtime Error

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

dp = [C] * K
#dp[k][n:位置] nからk回以内に到達できる最大ポイント

for k in range(1, K):
  for n in range(N):
    next = P[n] - 1
    dp[k][n] = max(dp[k-1][next], dp[k-1][next]+C[next])
    print(dp)
  

print(max(dp[K-1]))

Submission status: Runtime Error

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

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

def move(pre,score,optimal,remain):
    if remain==0:
        #print("optimal",optimal)
        return optimal
    else:
        score += C[P[pre]]
        optimal = max(optimal,score)
        #print("score",score)
        remain -= 1
        return move(P[pre],score,optimal,remain)


ans_l = []
for i in range(N):
    temp = move(i,0,-1000000000,K)
    ans_l.append(temp)
    #print("===============")

#print(ans_l)
ans = max(ans_l)
print(ans)

Submission status: Runtime Error

Solution code:


def li():
    return [int(x) for x in input().split()]

N, K = li()
P = [0] + li()
C = [0] + li()
max_scores = [-10**12] * (N+10)
for init_i in range(1, N+1):
    i = init_i
    scores = [-10**9] * (K+10000)
    scores[0] = 0
    for l in range(1, K+1):
        i = P[i]
        scores[l] = scores[l-1] + C[i]
    scores[0] = -10**12
    max_scores[i] = max(scores)
print(max(max_scores))

Submission status: Runtime Error

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10**9)
INF = 10**9
mod = 10**9+7


def solve(array):
    best_sum = float('-inf')
    best_start = best_end = -1
    current_sum = 0
    current_start = 0
    cnty = 0
    for current_end, num in enumerate(array):
        if current_sum <= 0:
            current_start = current_end
            current_sum = num
        else:
            current_sum += num
        if current_end-current_start+1 > K:
            current_start += 1
            current_sum -= array[cnty]
            cnty += 1
        if current_sum > best_sum:
            best_sum = current_sum
            best_start = current_start
            best_end = current_end

    return best_sum

N,K = I()
P = l()
C = l()
L = [[] for _ in range(N)]
a = [0]*N
cnt = 0
ans = 0
for j in range(N):
    if a[j] == 0:
        cnt += 1
        Pi = j+1
        for i in range(N):
            Pi = P[Pi - 1]
            a[Pi-1] = 1
            L[cnt-1].append(C[Pi - 1])
            if Pi == j+1:
                break
for i in range(N):
    if L[i]:
        L[i] = L[i]*(K//len(L[i])+1)
        ans = max(ans,solve(L[i]))
        if ans == 0 and i == 0:
            ans = solve(L[i])
print(ans)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
p = list(map(int,input().split()))
for i in range(len(p)):
    p[i]-=1
c = list(map(int,input().split()))

def big(m,l,init=-10**9):
    ret = -10**9
    ll = l + l + l
    for i in range(1,m+1):
        ret_ = sum(l[:i])
        su = ret_
        for j in range(len(l)):
            su += ll[i+j] - ll[j]
            ret_ = max(ret_,su)
        ret = max(ret,ret_)
    return max(ret,init)

visited = [False]*n

def dfs(l,v):
    if visited[v]:
        return l
    visited[v] = True
    return dfs(l + [c[v]],p[v])

ret = -10**9
for i in range(n):
    l = dfs([],i)
    #print(l)
    if not len(l):
        continue
    if k//len(l) > 0:
        ret = max(ret,sum(l)*(k//len(l))+big(k%len(l),l,0))
        ret = max(ret,big(len(l),l))
        ret = max(ret,sum(l)*(k//len(l)-1)+big(len(l),l))
    else:
        ret = max(ret,big(k,l))

print(ret)

Submission status: Runtime Error

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


def f(x):
    num_list = []
    score_list = []
    while True:
        if p[x] in num_list:
            return score_list
        score_list.append(c[x])
        num_list.append(p[x])
        x = p[x]
ans = 0
for i in range(n):
    score_list = f(i)
    score = (k // len(score_list)) * sum(score_list)
    for j in range(k % len(score_list)):
        if score_list[i] > 0:
            score += score_list[i]
    if ans < score:
        ans = score

print(ans)

Submission status: Runtime Error

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

ans = -float("inf")

# O(N)
for start in range(N):
    seen = [False] * N 
    cycle = []
    score = []
    
    seen[start] = True
    cycle.append(start)
    score.append(C[start])

    now = start
    # 鳩ノ巣原理からこのループは max 5000 しか回らない O(N)
    while True:
        nxt = P[now]-1
        if seen[nxt]:
            break
        
        cycle.append(nxt)
        score.append(C[nxt])

        now = nxt
    sum_v = sum(score)
    # 累積和
    score_sum = [ 0 for _ in range(len(score) + 1)]
    for i in range(len(score)):
        score_sum[i+1] = score_sum[i] + score[i]

    t_ans = max(score_sum[:min(K, len(score_sum))] - C[start])

    #print(score_sum)
    #print(score_sum[:((K+1) % len(cycle))])
    
    if sum_v >= 0:
        aa = 0
        aa += (sum_v - C[start]) if K > len(cycle) else 0
        aa += sum_v * (K // len(cycle) - 1)
        nn = K % len(cycle)
        score_sum += score_sum[1:]
        if nn != 0:
            aa += max(score_sum[:nn+2])
        t_ans = max(t_ans, aa)
    else:
        t_ans = max(score_sum[:min(K, len(score_sum))]) - C[start]

    ans = max(ans, t_ans)

print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np

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

scores = np.zeros((N,K))

for i in range(N):
    position = i
    for k in range(K):
        if k == 0:
            scores[i][k] = C[P[position]-1]
        else:
            scores[i][k] = C[P[position]-1] + scores[i][k-1]
        position = P[i]-1

print(int(scores.max()))

Submission status: Runtime Error

Solution code:
# n=int(input())
n,k=map(int,input().split())
P=list(map(int,input().split()))
P=[i-1 for i in P]
C=list(map(int,input().split()))
ans=-float("inf")
for i in range(n):
    dp=[-float("inf")]*(n+2)
    kai=0
    dp[kai]=C[P[i]]
    now=P[i]
    bef=i
    while now!=i:
        kai+=1
        if kai>=k:break
        dp[kai]= dp[kai-1]+C[P[now]]
        now=P[now]
    #if dp[0]==max(dp):dp[0]=-float("INF")

    if kai>=k: ans=max(ans,max(dp));continue
    kai+=1
    t=k%kai
    ans=max(ans, dp[kai-1]*(k//kai) + max(dp[:t]) )
    
print(ans)

Submission status: Runtime Error

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


Cum = [0]*(N+2)
temp = 1
SUM = 0
for i in range(N+1):
    temp = P[temp-1]
    SUM += C[temp-1]
    Cum[i+1] += SUM
    
 
    

group = []
group_C = []
group_Cum = []

check = [1]*N

while sum(check)!=0:
    temp = []
    start_num = check.index(1)+1
    temp_p = P[start_num-1]
    check[temp_p-1] -= 1
    temp.append(temp_p)
    
    temp_c = C[temp_p-1]
    
    temp_Cum = [0]
    temp_Cum.append(temp_c)
    
    for i in range(N):
    
        temp_p = P[temp_p-1]
        check[temp_p-1] -= 1
        temp.append(temp_p)
        temp_c += C[temp_p-1]
        temp_Cum.append(temp_c)
                
        if temp_p == start_num:
            break
    
    for i in range(len(temp)):
        temp_Cum.append(temp_c+temp_Cum[1+i])
    
    
    group.append(temp)
    group_C.append(max(0,temp_c))
    group_Cum.append(temp_Cum)
    
ans = -10**12

for i in range(len(group_C)):
    X = len(group[i])
    Y = K//X
    Z = K%X
       
    group_max = -10**12
    for k in range(1,Z+1):

        for j in range(X):
            group_max = max(group_max,group_Cum[i][k+j]-group_Cum[i][j])
            
        
        ans = max(ans,group_max+Y*group_C[i])
        
    if Y == 1:
        Z += X
        
        for k in range(1,Z+1):

            for j in range(X):
                group_max = max(group_max,group_Cum[i][k+j]-group_Cum[i][j])
                

            ans = max(ans,group_max+Y*group_C[i])
    
print(ans)

Submission status: Runtime Error

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

def li():
    return [int(x) for x in input().split()]


N, K = li()
P = [0] + li()
C = [0] + li()
max_scores = [-10**12] * (N+10)
for init_i in range(1, N+1):
    i = init_i
    scores = [-10**9] * (10**5)
    scores[0] = 0
    for l in range(1, K+1):
        i = P[i]
        scores[l] = scores[l-1] + C[i]
    scores[0] = -10**12
    max_scores[i] = max(scores)
print(max(max_scores))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))
scores = list()
max_list = list()
for i in range(N):
    next = Ps[i] - 1
    scores = [Cs[next]]
    while next != i:
        next = Ps[next] - 1
        scores.append(Cs[next]+scores[-1])
    l = len(scores)
    if scores[-1] <= 0:
        if K <= l:
            max_list.append(max(scores[:K]))
        else:
            max_list.append(max(scores))
    else:
        if K <= l:
            max_list.append(max(scores[:K]))
        else:
            a, b = divmod(K, l)
            max_list.append(a*scores[-1] + max(scores[:b]))
    #print(scores)
print(max(max_list))

Submission status: Runtime Error

Solution code:
from itertools import accumulate
N, K = map(int, input().split())
P = [i-1 for i in map(int, input().split())]
C = list(map(int, input().split()))

seen = [0] * N

ans = -10**20

for i in range(N):
    if not seen[i]:
        seen[i] = 1
        loop = [C[i]]
        while True:
            i = P[i]
            if seen[i]:
                break
            seen[i] = 1
            loop.append(C[i])
        L = len(loop)
        loop = loop + loop
        loop = [0] + list(accumulate(loop))
        if loop[L] <= 0:
            move = min(L, K)
            for i in range(L):
                for j in range(1, move + 1):
                    ans = max(ans, loop[i + j] - loop[i])
        else:
            if K > L:
                continue
                div, mod = divmod(K, L)
                tmp = div * loop[L]
                move = min(mod, L)
                if move:
                    for i in range(L):
                        for j in range(1, move + 1):
                            ans = max(ans, tmp + loop[i + j] - loop[i])
                else:
                    ans = max(ans, tmp)
                tmp = (div - 1) * loop[L]
                move = L
                for i in range(L):
                    for j in range(1, move + 1):
                        ans = max(ans, tmp + loop[i + j] - loop[i])
            else:
                move = K
                for i in range(L):
                    for j in range(1, move + 1):
                        ans = max(ans, tmp + loop[i + j] - loop[i])

print(ans)

Submission status: Runtime Error

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10**9)
INF = 10**9
mod = 10**9+7


def solve(array):
    best_sum = float('-inf')
    best_start = best_end = -1
    current_sum = 0
    current_start = 0
    cnty = 0
    for current_end, num in enumerate(array):
        if current_sum <= 0:
            current_start = current_end
            current_sum = num
        else:
            current_sum += num
        if current_end-current_start+1 > K:
            current_start += 1
            current_sum -= array[cnty]
            cnty += 1
        if current_sum > best_sum:
            best_sum = current_sum
            best_start = current_start
            best_end = current_end

    return best_sum

N,K = I()
P = l()
C = l()
L = [[] for _ in range(N)]
a = [0]*N
cnt = 0
ans = 0
for j in range(N):
    if a[j] == 0:
        cnt += 1
        Pi = j+1
        for i in range(N):
            Pi = P[Pi - 1]
            a[Pi-1] = 1
            L[cnt-1].append(C[Pi - 1])
            if Pi == j+1:
                break
for i in range(N):
    if L[i]:
        L[i] = L[i]*(K//len(L[i])+2)
        ans = max(ans,solve(L[i]))
        if ans == 0 and i == 0:
            ans = solve(L[i])
print(ans)

Submission status: Runtime Error

Solution code:
N , K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
x = 0
y = 1
ans = -10 ** 9
k = K
A = [-10 ** 9] * (N * K)
z = 0


for i in range(N):
    x = P[i]
    while K > 0:
        y += C[x - 1]
        x = P[x - 1]
        A[z] = y
        z += 1
        
        K -= 1
        
        

        
    y = 0
    K = k

A = sorted(A, reverse = True)
print(A[0])

Submission status: Runtime Error

Solution code:

#"""
N, K = [int(n) for n in input().split(" ")]
Ps = [int(n) for n in input().split(" ")]
Cs = [int(n) for n in input().split(" ")]
#"""
"""
N = 10
K = 58
Ps = [9, 1, 6, 7, 8, 4, 3, 2, 10, 5]
Cs = [695279662, 988782657, -119067776, 382975538, -151885171, -177220596, -169777795, 37619092, 389386780, 980092719]
"""
"""
N = 3
K = 3
Ps = [3, 1, 2]
Cs = [-1000,-2000,-3000]
"""

circles = []
already = {}
for p in range(N):
    if p not in already:
        tmp = []
        nowp = p
        while nowp not in tmp:
            tmp.append(nowp)
            already[nowp] = 1
            nowp = Ps[nowp] - 1
        circles.append(tmp)

#print(circles)

finalResult = -100000000000

def getCircleScore(circle, start, kk):
    #print(circle, start, kk)
    s = 0
    for k in range(kk):
        index = start + k
        if index >= len(circle):
            index = index % len(circle)
        s += Cs[circle[index]]
    return s


maxCircle = []
maxCircleScore = -10000000000
maxIndex = 0
for circle in circles:
    CircleSum = sum([Cs[n] for n in circle])
    if maxCircleScore <= CircleSum:
        maxCircleScore = CircleSum
        maxCircle = circle

for circle in [maxCircle]:
#for circle in circles:
    
    CircleSum = sum([Cs[n] for n in circle])
    #print(circle, CircleSum)
    score = 0
    if CircleSum > 0:
        score = K // len(circle) * CircleSum

    K = K % len(circle)
    if K == 0:
        K = len(circle)

    maxScore = -100000000000
    for start in range(len(circle)):
        #print("start", start)
        for kk in range(1, K+1):
            s = getCircleScore(circle, start, kk)
            #print(s)
            if maxScore <= s:
                maxScore = s

    final = score + maxScore

    if final >= finalResult:
        finalResult = final

print(finalResult)

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
scores = []
for i in range(N):
  pos = P[i]-1
  s = [C[i]]
  j = 1
  while j < K and pos != i:
    s.append(s[-1]+C[pos])
    pos = P[pos]-1
    j += 1
  smax = max(s)
  length = len(s)
  if length < K and s[-1] > 0:
    smod = s[:K%length]
    smodmax = max(smod)
    scores.append(max(s[-1] * ((K//length)-1) + smax, s[-1] * (K//length), s[-1] * (K//length) + smodmax))
  else:
    scores.append(smax)
print(max(scores))

Submission status: Runtime Error

Solution code:
import sys
input = lambda:sys.stdin.readline().rstrip()

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):
    now_s = C[i]
    S = [C[i]]
    pre = [i]
    cur = i    
    while True:
        if P[cur]-1 in pre:
            break
        cur = P[cur] - 1
        pre.append(cur)
        now_s += C[cur]
        S.append(now_s)
    #print(score)
    #print(S)
    #print(pre)
    L = len(S)    
    if K <= L-1:
        ans = max(ans,max(S[1:K])-S[0])
    else:
        Sum = S[-1]
        if Sum <= 0:
            ans = max(ans,max(S[1:K])-S[0])
        else:
            if K % L == 0:
                ans = max(ans, (Sum * (K // L -1)) + max(S[1:K])-S[0])
            elif K % L == 1:
                ans = max(ans, (Sum * (K // L)) + max(0,S[1]-S[0]))
            else:
                ans = max(ans, (Sum * (K // L)) + max(S[1:K%L+1])-S[0])
                #print(S[1:K%L])
print(ans)

Submission status: Runtime Error

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

for i in range(n):
    p[i]-=1

maxpoints=[]
points=[]

for i in range(n):
    gone=set([])
    now=i
    next=p[now]
    point=c[next]
    maxpoint=[point]
    gone.add(i)

    for j in range(min(k,n)):
        now=next
        next=p[now]
        if next in gone:
            point+=c[next]
            maxpoint.append(max(maxpoint[-1],point))
            maxpoints.append(maxpoint)
            points.append(point)
            break
        point+=c[next]
        gone.add(now)
        maxpoint.append(max(maxpoint[-1],point))

#print(maxpoints)
#print(points)

ans=-float('inf')

for i in range(n):
    if k<=len(maxpoints[i]):
        temp=maxpoints[i][k-1]
    elif points[i]<=0:
        temp=maxpoints[i][-1]
    else:
        times=k//len(maxpoints[i])
        odd=k%len(maxpoints[i])
        temp=points[i]*times+maxpoints[i][odd-1]
    ans=max(temp,ans)
print(ans)

Submission status: Runtime Error

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

def li():
    return [int(x) for x in input().split()]


N, K = li()
P = [0] + li()
C = [0] + li()
max_scores = [-10**12] * (N+10)
K = 10**9
for init_i in range(1, N+1):
    i = init_i
    scores = [-10**9] * (K+1)
    scores[0] = 0
    for l in range(1, K+1):
        i = P[i]
        scores[l] = scores[l-1] + C[i]
    scores[0] = -10**12
    max_scores[i] = max(scores)
print(max(max_scores))

Submission status: Runtime Error

Solution code:
n,k = map(int, input().split())
p = list(map(int, input().split())) 
c = list(map(int, input().split()))
g = []
for i in range(n):
  ans=c[i]
  e =[ans]
  f = i
  a = 1
  while a<k:
    i = p[i]-1
    if i == f:
      break
    a+=1
    ans+=c[i]
    e.append(ans)
  if e[-1]>0 and a<k:
    w = k%len(e)
    y = k//len(e)*e[-1]+max(e[:w])
    g.append(y)
  else:
    g.append(max(e))
print(max(g))

Submission status: Runtime Error

Solution code:
from itertools import accumulate


def main():
    cells, moves = [int(x) for x in input().split()]
    nexts = [int(x) - 1 for x in input().split()]
    scores = [int(x) for x in input().split()]

    ans = -10 ** 9 - 5
    # whole_break = False
    for start in range(cells):
        route = []
        seen = set()
        route_append = route.append
        seen_add = seen.add
        now = start
        for _step in range(cells):
            nex = nexts[now]
            # if nex < start:
            #     whole_break = True
            #     break
            if nex in seen:
                break
            route_append(scores[nex])
            seen_add(nex)
            now = nex

        length = len(route)
        total = sum(route)
        # if whole_break:
        #     whole_break = False
        #     if moves > length:
        #         break

        if total > 0 and moves > length:
            q, mod = divmod(moves, length)
            candidate = max(list(accumulate(route))[:mod]) + total * q
        else:
            candidate = max(list(accumulate(route))[:min(moves, length)])
        ans = max(ans, candidate)

    print(ans)


if __name__ == '__main__':
    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()))
p.insert(0, 0)
c.insert(0, 0)
now = 0
add = 0
ans = -100000000000
l = [0]*(n+1)

now = 1
for i in range(1,n+1):
    now = p[now]
    add += c[now]
    l[i] = add


for j in range (n):
    y = 0
    while i + k <= n:
        y += l[n] - l[i] + l[i-1]
        k -= n
    y += l[i+k] - l[i]
    
    if y > ans:
        ans = y
print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = lambda:sys.stdin.readline().rstrip()

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):
    now_s = C[i]
    S = [C[i]]
    pre = [i]
    cur = i    
    while True:
        if P[cur]-1 in pre:
            break
        cur = P[cur] - 1
        pre.append(cur)
        now_s += C[cur]
        S.append(now_s)
    #print(score)
    #print(S)
    #print(pre)
    L = len(score)    
    if K <= L-1:
        ans = max(ans,max(S[1:K])-S[0])
    else:
        Sum = S[-1]
        if Sum <= 0:
            ans = max(ans,max(S[1:K])-S[0])
        else:
            if K % L == 0:
                ans = max(ans, (Sum * (K // L -1)) + max(S[1:K])-S[0])
            elif K % L == 1:
                ans = max(ans, (Sum * (K // L)) + max(0,S[1]-S[0]))
            else:
                ans = max(ans, (Sum * (K // L)) + max(S[1:K%L+1])-S[0])
                #print(S[1:K%L])
print(ans)

Submission status: Runtime Error

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

def move(limit,state, score,max_score):
    if limit <= 0:
#        print("max_score: " + str(max_score))
        return max_score
    else:
        state = p[state]-1
        score += c[state]
#        print(state)
#        print(limit,state,score)
        if max_score < score:
            max_score = score
        return move(limit-1,state,score,max_score)

score_list = []
for i in range(n):
    score_list.append(move(k-1,p[i]-1,c[p[i]-1],c[p[i]-1]))
#print(score_list)

print(max(score_list))

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()]
x = 0
if k > n and sum(c) > 0:
    l = k // n
    k = k % n
    x = 1
v_list = []
for i in range(n):
    v = 0
    q = p[i]
    pre_v = 0
    pre_v_list = []
    for j in range(k):
        pre_v += c[q - 1]
        pre_v_list.append(pre_v)
        q = p[q - 1]
        if j >= n:
            break
    v = max(pre_v_list)
    if x == 1:
        v += (sum(c) * l)
    v_list.append(v)
print(max(v_list))

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
p = [i-1 for i in map(int,input().split())]
c = list(map(int,input().split()))
lope_list = []
p_ = p.copy()
while p_ != []:
    l = []
    check_index = []
    a = p_[0]
    while 1:
        if a in check_index:
            break
        else:
            l.append(c[a])
            check_index.append(a)
            a = p[a]
    lope_list.append(l)
    for i in check_index: p_.remove(i)
ans = - float('inf')
for i in lope_list:
    d = 0
    if k > len(i):
        if sum(i)>0:
            r = k//len(i)
            d += r*sum(i)
            k -= r*len(i)
    m = i+i
    for k1 in range(1,k+1):
        dd = d + sum(m[:k1])
        ans = max(dd,ans)
        for k2 in range(1,len(i)):
            dd = dd - m[k2-1] + m[k1+k2-1]
            ans = max(dd,ans)
print(ans)

Submission status: Runtime Error

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

max_list = []
for i in range(1, N + 1):
    point = []
    p = 0
    buf = i
    while P[buf] != i:
        buf = P[buf]
        p += C[buf]
        point.append(p)
    buf = P[buf]
    p += C[buf]
    point.append(p)

    if point[-1] <= 0:
        if len(point) > K:
            max_list.append(max(point[:K]))
        else:
            max_list.append(max(point))
    else:
        if len(point) > K:
            max_list.append(max(point[:K]))
        else:
            division, mod = divmod(K, len(point))
            max_list.append(division * point[-1] + max(point[:mod]))
ans = max(max_list)
print(ans)