Problem:


Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
p = list(map(int,input().split()))
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
    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))
    else:
        ret = max(ret,big(k,l))

print(ret)

Submission status: Runtime Error

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



def main():
    n, k = map(int, input().split())
    p = [int(x)-1 for x in input().split()]
    c = list(map(int, input().split()))
    
    doubling = [[0]*n for i in range(20)]
    doubling_max = [[0]*n for i in range(20)]
    place = [[0]*n for i in range(20)]
    
    ans = -1000000000
    for i in range(n):
        sub = c[p[i]]
        if sub >= 0:
            break
        if ans < sub:
            ans = sub
        if i == n-1:
            print(ans)
            sys.exit()
            
    
    for i in range(20):
        if i == 0:
            for j in range(n):
                doubling[i][j] = c[p[j]]
                place[i][j] = p[j]
            continue
        for j in range(n):
            place[i][j] = place[i-1][place[i-1][j]]
            doubling[i][j] = doubling[i-1][j]+doubling[i-1][place[i-1][j]]
    
    for i in range(20):
        if i == 0:
            for j in range(n):
                doubling_max[i][j] = doubling[i][j]
            continue
        for j in range(n):
            doubling_max[i][j] = max(doubling_max[i-1][j], doubling[i-1][j]+doubling_max[i-1][place[i-1][j]])
    
    ans = 0
    judge = []
    key = 0
    while k:
        if k%2:
            judge.append(key)
        k //= 2
        key += 1
    judge.reverse()
    
    for i in range(n):
        pl = i
        key = 0
        for j in range(len(judge)):
            if ans < key+doubling_max[judge[j]][pl]:
                ans = key+doubling_max[judge[j]][pl]
            key += doubling[judge[j]][pl]
            pl = place[judge[j]][pl]
        

    print(ans)
        
    


    
    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
import itertools as it
import collections as cl
import math
from functools import reduce

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


N, K = li()
P = [0] + li()
C = [0] + li()

max_scores = [-10**12] * (N+1)
for init_i in range(1, N+1):
    i = init_i
    scores = [-10**12] * (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())
k = k+1
p = [0] * n
c = [0] * n
a = [0] * (n+1)
ans = [0] * n

p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
    s = 0
    x = i
    roop = 0
    for j in range(n):
        s += c[x]
        a[j+1] = s
        x = p[x] - 1
        if x == i:
            roop = j + 1
            break
    if s < 0:
        ans[i] = max(a[1:min(roop, k-1)])
    else:
        ans[i] = max(s * (k // roop) + max(a[:k % roop]), s * (k // roop - 1) + max(a))
print(max(ans))

Submission status: Runtime Error

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

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

point = [0]*n;

for x in range(n):
    s = []
    i = x;
    while True:
        i = p[i]-1;
        s.append(c[i])
        if i == x:
            break;
    ss = len(s);
    t = [0]*ss
    t[0] = s[0]
    for y in range(1,ss):
        t[y]=t[y-1]+s[y];
    
    roop = t[ss-1]
    maxt = max(t);
    if roop <= 0:
        point[x] = maxt;
    else:
        roopa = k // ss
        roopb = k % ss
        roopc = (roop * roopa) + max(t[0:roopb])
        roopd = (roop *(roopa-1)) + maxt
        if roopc >= roopd:
            point[x] = roopc
        else:
            point[x] = roopd

print(max(point));

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
a=[]
ans=-10**10
for i in range(N):
    idx=P[i]-1
    z=set()
    rl=[]
    c=0
    tc=0
    while idx not in z and c<K:
        tc+=C[idx]
        rl.append(tc)
        ans=max(ans.tc)
        z.add(idx)
        idx=P[idx]-1
        c+=1
    if c<K:
        d,m=divmod(K,c)
        if m==0:
            d-=1
            m=c
        tc=d*tc
        tc+=max(rl[:m])
        ans=max(ans.tc)
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()))
N_max_list = [0] * N

for i in range(N):
    play = 0
    place = i
    score = 0
    memory = []
    local_max = -float("inf")
    lm_list = []
    while True:
        memory.append(place)
        place = P[place] - 1
        score += C[place]
        local_max = max(local_max, score)
        lm_list.append(local_max)
        play += 1
        if place in memory:
            if score > 0:
                N_max_list[i] = score * (K // play) + max(lm_list[:K % play])
            else:
                N_max_list[i] = local_max
            break
        if play == K:
            N_max_list[i] = local_max
            break
print(max(N_max_list))

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:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

# ループを見つける(5000), 一周のスコアを確認
is_visit = [0 for _ in range(n)]
loop = []

def search(i, j):
    if is_visit[i] == 0:
        is_visit[i] = j
        l.append(i)
        search(p[i]-1, j)
    else:
        pass

loop_id = 1
for i in range(n):
    l = []
    search(i, loop_id)
    if len(l) != 0:
        loop.append(l)
        loop_id += 1
# print(loop)
# print(is_visit)

ans = [0 for _ in range(n)]
for i in range(n):
    # i からはじめて最大スコア
    l = loop[is_visit[i]-1] # 所属するループ
    tmp1 = 0 # ループによるスコア
    tmp_k = k
    s = 0
    for j in range(len(l)):
        s += c[l[j]]
    if s > 0 and k > len(l):
        # 回るほどお得で一周より回れる
        tmp1 += s*(tmp_k//len(l))
        tmp_k -= (tmp_k//len(l))*len(l)
    else:
        tmp_k -= (tmp_k//len(l))*len(l)
        if tmp_k == 0:
            tmp_k = len(l)
    pointer = p[i]
    tmp2 = [c[pointer-1] for _ in range(tmp_k)] # 愚直に進んだ点数
    if tmp_k != 0:
        for j in range(1, tmp_k):
            # k回目までの累積和で最大を求める
            pointer = p[pointer-1]
            tmp2[j] = tmp2[j-1] + c[pointer-1]
    # print(i, l, s, tmp_k, tmp1, tmp2)
    if len(tmp2) != 0:
        ans[i] = tmp1 + max(tmp2)
    else:
        ans[i] = tmp1
# print(ans)
print(max(ans))

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
    cnt = 0
    c_sum = [0]
    s = set()
    while True:
        s.add(now)
        c_sum.append(c_sum[-1] + c[now])
        now = p[now]
        cnt += 1
        if now in s:
            break
    if k <= cnt:
        ans = max(ans, max(c_sum[1: min(k + 1, len(c_sum) - 1)]))
    else:
        temp = c_sum[-1]
        q = k // cnt
        temp *= q
        q = k - q*cnt
        temp += max(c_sum[1:min(q + 1, len(c_sum) - 1)])
        ans = max(ans, temp, max(c_sum[1:]))
print(ans)

Submission status: Runtime Error

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



def main():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    
    doubling = [[0]*n for i in range(20)]
    doubling_max = [[0]*n for i in range(20)]
    place = [[0]*n for i in range(20)]
    
    ans = -1000000000
    for i in range(n):
        sub = c[p[i]-1]
        if sub >= 0:
            break
        if ans < sub:
            ans = sub
        if i == n-1:
            print(ans)
            sys.exit()
            
    
    for i in range(20):
        if i == 0:
            for j in range(n):
                doubling[i][j] = c[p[j]-1]
                place[i][j] = p[j]
            continue
        for j in range(n):
            place[i][j] = place[i-1][place[i-1][j]-1]
            doubling[i][j] = doubling[i-1][j]+doubling[i-1][place[i-1][j]-1]
    
    for i in range(20):
        if i == 0:
            for j in range(n):
                doubling_max[i][j] = doubling[i][j]
            continue
        for j in range(n):
            doubling_max[i][j] = max(doubling_max[i-1][j], doubling[i-1][j]+doubling_max[i-1][place[i-1][j]-1])
    
    ans = 0
    judge = []
    key = 0
    while k:
        if k%2:
            judge.append(key)
        k //= 2
        key += 1
    judge.reverse()
    #print(doubling_max)
    for i in range(n):
        pl = i+1
        key = 0
        for j in range(len(judge)):
            if ans < key+doubling_max[judge[j]][pl-1]:
                ans = key+doubling_max[judge[j]][pl-1]
            key += doubling[judge[j]][pl-1]
            pl = place[judge[j]][pl-1]
        

    print(ans)
        
    


    
    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:

n, k = map(int, input().split())
k = k+1
p = [0] * n
c = [0] * n
a = [0] * (n+1)
ans = [0] * n

p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
    s = 0
    x = i
    roop = 0
    for j in range(n):
        s += c[x]
        a[j+1] = s
        x = p[x] - 1
        if x == i:
            roop = j + 1
            break
    if s < 0:
        ans[i] = max(a[1:min(roop, k)])
    else:
        ans[i] = max(s * (k // roop) + max(a[:k % roop]), s * (k // roop - 1) + max(a))
print(max(ans))

Submission status: Runtime Error

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

for n in range(N):
  temp_cost=0
  next_n=n
  for k in range(K):
    temp_cost+=C[P[next_n]-1]
    cost_list.append(temp_cost)
    next_n=P[P[next_n]-1]
print(min(cost_list))

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<=n:
        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
import numpy as np
input = sys.stdin.buffer.readline
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))


def f(n):
    _P = []
    _C = []
    i = n
    while True:
        if P[i] in _P:
            break
        _P.append(P[i])
        _C.append(C[P[i]])
        i = P[i]
    # print(f'{_P=}, {_C=}')
    if len(_P) < K:  # ぐるぐる回れる
        cumsum = np.array(_C).cumsum()
        if cumsum[-1] <= 0:  # cumsumの最後が0以下だったらぐるぐる回らずmaxのところでやめる
            ans = cumsum.max()
            # print(f'case 1 {cumsum=}, {ans=}')
            return ans
        div, mod = divmod(K, len(_P))
        ans = div * cumsum[-1]
        ans = max(ans, ans + cumsum[:mod].max())
        return ans
    else:
        cumsum = np.array(_C[:K]).cumsum()
        ans = cumsum.max()
        # print(f'{cumsum=}, {ans=}')
        return ans


# f(1)
# print('')
# f(2)
# print('')
# f(3)
# print('')
# f(4)
# print('')
# f(5)

ans = f(1)
for i in range(1, N + 1):
    ans = max(ans, f(i))
# print(f'last answer = {ans}')
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
ans = -1000000000
for i in range(N):
  cost = 0
  S = []
  x = P[i] - 1
  l = 1
  while 1:
    cost += C[x]
    S.append(cost)
    if x == i:
      break
    l += 1
    x = P[x] - 1
  if cost > 0:
    if K % l != 0:
      ans = max(ans, cost * (K // l) + max(S[:K % l]), cost * ((K // l) - 1) + max(S))
    else:
      ans = max(ans, cost * (K // l))
  else:
    ans = max(ans, max(S[:min(K, L)]))
print(ans)

Submission status: Runtime Error

Solution code:
X, K, D  = map(int, input().split())
shou = X//D
amari = X%D 

if D * K <= X:
    print(X - (D*K) + 2)
else:
    nokori = K - shou
    if nokori % 2 == 0:
        print(amari)
    else:
        print(abs(amari - D))

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
    cnt = 0
    c_sum = [0]
    s = set()
    while True:
        s.add(now)
        c_sum.append(c_sum[-1] + c[now])
        now = p[now]
        cnt += 1
        if now in s:
            break
    if k <= cnt:
        ans = max(ans, max(c_sum[1: min(k + 1, len(c_sum))]))
    else:
        temp = c_sum[-1]
        if cnt == 0:
            continue
        q = k // cnt
        temp *= q
        q = k - q*cnt
        temp += max(c_sum[1:min(q + 1, len(c_sum))])
        ans = max(ans, temp, max(c_sum[1:]))
print(ans)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;

const int N = 5005;
int p[N], n, k;
long long c[N], score[N]; 

long long cal(int x) {
    int s = x, cnt = 0;
    long long ret = 0;
    memset(score, 0, sizeof(score));
    do {
        s = p[s];
        ret += c[p[s]];
        cnt++;
        score[cnt] = ret;
    } while (s != x && cnt < k);
    if (cnt <= k) ret = ret * (k / cnt) + score[k % cnt];
    for (int i = 1; i <= min(k, cnt); i++) ret = max(ret, score[i]); 
    return ret;
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);

    cin >> n >> k;
    for (int i = 1; i <= n; i++) cin >> p[i];
    for (int i = 1; i <= n; i++) cin >> c[i];
    long long ans = -1e18;
    for (int i = 1; i <= n; i++) ans = max(ans, cal(i));
    cout << ans << '\n';
}

Submission status: Runtime Error

Solution code:
import itertools
N,K = [int(i) for i in input().split()]
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
places = []
n = 0
i = 0
T = list(range(1,N))
while n < N:
    L = [i]
    n += 1
    for _ in range(N):
        if not P[i] in L:
            i = P[i]
            T.remove(i)
            L.append(i)
            n += 1
        else:
             break
    places.append(L)
    if T:
        i = T[0]
scores = []
for L in places:
    s = 0
    M = []
    for l in L:
        s += C[l]
        M.append(s)
    scores.append(M)
ans = -(10**9)
for L in scores:
    l = len(L)
    for i,j in itertools.combinations(range(l),2):
        if j-i <= K:
            n = 0
            if L[-1] > 0:
                n = L[-1] * ((K-j+i)//l)
            ans = max(ans, L[j]-L[i]+n)
        if N-j+i <= K:
            n=0
            if L[-1]>0:
                n= L[-1] * ((K-l+j-i)//l)
            ans = max(ans,L[i] + L[-1] - L[j]+n)
print(ans)

Submission status: Runtime Error

Solution code:
import math
n,k = map(int,input().split())
plist= list(map(int,input().split()))
clist= list(map(int,input().split()))

n_max = [[] for _ in range(n)]

for i in range(n):
    start = plist[i]-1
    score = 0
    first = start
    for j in range(n):
        if j != 0 and start == first:
            break
        score += clist[start]
        start = plist[start]-1
        n_max[i].append(score)

max_score = -math.inf
for i in range(n):
    i_score = n_max[i]
    if k < n:
        score = max(i_score[0:k])
    elif k >= n and i_score[-1] > 0:
        score = (k//len(i_score))*i_score[-1]+max(i_score[0:(k-(k//len(i_score)*len(i_score)))])
    else:
        score = max(i_score[0:k])
    max_score = max(score,max_score)

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

ans=[]
for i in range(N):
    trace=[-1 for _ in range(N)]
    cand=[0]
    trace[i]=0
    pos=i
    cnt=1
    cond=False
    while cnt<=K:
        pos=P[pos]-1
        if trace[pos]==-1:
            cand.append(cand[-1]+C[pos])
            trace[pos]=cnt
            cnt+=1
        else:
            cond=True
            init=trace[pos]
            loop=cnt-init
            point=cand[-1]+C[pos]-cand[init]
            break
    if cond:
        cand.append(cand[init]+(K-init)//loop*point+max(cand[init+1:init+(K-init)%loop+1])-cand[init])
    ans.append(max(cand[1:]))
print(max(ans))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = [*map(int, input().split())]
C = [*map(int, input().split())]
 
V = [0] * N
V_max = [0] * K
for j in range(K):
  V_pre = V
  V = [C[i] + V_pre[P[i]-1] for i in range(N)]
  V_max[j] = max(V)
print(max(V_max))

Submission status: Runtime Error

Solution code:

n, k = map(int, input().split())
k = k+1
p = [0] * n
c = [0] * n
a = [0] * (n+1)
ans = [0] * n

p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
    s = 0
    x = i
    roop = 0
    for j in range(n):
        s += c[x]
        a[j+1] = s
        x = p[x] - 1
        if x == i:
            roop = j + 1
            break
    if s < 0:
        ans[i] = max(a[1:min(roop, n)])
    else:
        ans[i] = max(s * (k // roop) + max(a[:k % roop]), s * (k // roop - 1) + max(a))
print(max(ans))

Submission status: Runtime Error

Solution code:
# from quantize import Decimal
X, K, D = list(map(int, input().split()))

dist= (X/D-K)/2
# print(dist)

if -dist > K :
    i = K
elif dist > 0 :
    i = 0
else :
    i = -round(dist)

# print(i)
print(abs(X + i*D - ((K-i)*D)))

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 = []
for i in range(n):
    visit = [-1 for i in range(n)]
    cou = 0
    visit[i] = 0
    kar = []
    now = i
    while True:
        cou += 1
        if cou > k:
            break
        nex = p[now] - 1
        if visit[nex] == -1:
            visit[nex] = cou
            if kar:
                kar.append(kar[-1] + c[nex])
            else:
                kar.append(c[nex])
            now = nex
        elif visit[nex] != -1:
            if kar:
                lokz = cou
                losu = kar[-1] + c[nex]
                if losu > 0:
                    kar.append(losu * (k//lokz) + max(kar[:(k%lokz)]))
                break
            else:
                if c[nex] >= 0:
                    kar.append(c[nex]*k)
                elif c[nex] < 0:
                    kar.append(c[nex])
                break
    ans.append(max(kar))
print(max(ans))

Submission status: Runtime Error

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
if K == 1:
    print(max(C))
    import sys
    sys.exit()
uf = UnionFind(N)
for i in range(N):
    uf.union(i, P[i]-1)

ans = -float("inf")
for x in uf.all_group_members().values():
    n = len(x)
    m_score = [-float("inf")] * n
    sum_c = 0
    for i in x:
        tmp_score = 0
        tmp_pos = i
        sum_c += C[i]
        for j in range(n):
            tmp_pos = P[tmp_pos]
            tmp_pos -= 1
            tmp_score += C[tmp_pos]
            m_score[j] = max(tmp_score, m_score[j])
    if K <= n:
        ans = max(ans, max(m_score[:K]))
    elif sum_c <= 0:
        ans = max(max(m_score), ans)
    else:
        ans = max(sum_c * (K//n) + max(m_score[:(K%n)]), ans)
print(ans)

Submission status: Runtime Error

Solution code:
from itertools import chain

N, K = map(int, input().split())
P_L = [int(x)-1 for x in input().split()]
C_L = [int(x) for x in input().split()]

s_l = [[0] * N for _ in range(N+1)]

for i in range(N):
    _p = i
    for j in range(1, N+1):
        _p = P_L[_p]
        s_l[j][i] = s_l[j-1][i] + C_L[_p]

if K <= N:
    _l = list(chain(*(s_l[:K+1])))
    print(max(_l[N:]))
else:
    _tmp = s_l[N][0]
    _l = list(chain(*s_l))
    if _tmp <= 0:
        print(max(_l[N:]))
    else:
        _c = K // N
        _n = K % N
        _ans_a = _tmp * _c + max(_l[N:_n*N])
        _ans_b = _tmp * (_c - 1) + max(_l[N:])
        print(max(_ans_a, _ans_b))

Submission status: Runtime Error

Solution code:
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
    for start in range(cells):
        route = []
        seen = [False] * cells
        now = start
        for _step in range(cells):
            nex = nexts[now]
            if seen[nex]:
                break
            route.append(scores[nex])
            now = nex
            seen[now] = True
        length = len(route)
        total = sum(route)
        if total > 0 and moves > length:
            q, mod = divmod(moves, length)
            candidate = max(sum(route[:x + 1]) for x in range(mod)) + total * q
        else:
            candidate = max(sum(route[:x + 1])
                            for x in range(max(min(moves, length), 1)))
        ans = max(ans, candidate)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:

from sys import stdin

import itertools

import copy

import collections






N,K = map(int,input().split())

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

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

ans = -10000000000

if K <= N:
    for i in range(N):
        count = 0
        tmp_point = 0
        nv = i
        while count < K:
            nvv = P[nv]
            nvv -= 1
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
    print(ans)
else:
    loop = [0]*N
    for i in range(N):
        count = 0
        check = [False]*N
        tmp_point = 0
        nv = i
        while True:
            nvv = P[nv]
            nvv -= 1
            if check[nvv] == True:
                break
            check[nvv] = True
            tmp_point += C[nvv]
            count += 1
            nv = nvv
            ans = max(ans, tmp_point)
        loop[i] = [tmp_point, count, i]
    loop.sort(reverse=True)
    max_volue =  loop[0][0]
    #print(loop)
    if 0 <= max_volue:
        new_ans = -10000000
        for value, counter, key in loop:
            if value != max_volue:
                break
            shou = K//counter
            amari = K%counter
            tmp_ans = value*shou
            new_ans = max(new_ans, tmp_ans)
            count = 0
            nv = key
            while count < amari:
                nvv = P[nv]
                nvv -= 1
                tmp_ans += C[nvv]
                count += 1
                nv = nvv
                new_ans = max(new_ans, tmp_ans)
        print(new_ans)
        
    else:
        print(max(max(loop),ans))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)
N, K = map(int, input().split())
P = list(map(int, input().split()))
for i in range(N):
    P[i] -= 1
C = list(map(int, input().split()))

def f(now, count, nowVal, maxVal):
    if count == K:
        # print(max(maxVal, nowVal + C[P[now]]))
        return max(maxVal, nowVal + C[P[now]])

    return f(P[now], count+1, nowVal+C[P[now]], max(maxVal, nowVal+C[P[now]]))

ans = -10**9
for i in range(N):
    ans = max(ans, f(i, 0, 0, -10**9))

print(ans)

Submission status: Runtime Error

Solution code:
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
if K == 1:
    print(max(C))
    import sys
    sys.exit()
uf = UnionFind(N)
for i in range(N):
    uf.union(i, P[i]-1)

ans = -float("inf")
for x in uf.all_group_members().values():
    n = len(x)
    m_score = [-float("inf")] * (n+1)
    sum_c = 0
    for i in x:
        tmp_score = 0
        tmp_pos = i
        sum_c += C[i]
        for j in range(n):
            tmp_pos = P[tmp_pos]
            tmp_pos -= 1
            tmp_score += C[tmp_pos]
            m_score[j+1] = max(tmp_score, m_score[j+1])
    if K <= n:
        ans = max(ans, max(m_score[1:K+1]))
    elif sum_c <= 0:
        ans = max(max(m_score), ans)
    else:
        ans = max(sum_c * (K//n) + max(m_score[1:(K%n)+1]), ans)
print(ans)

Submission status: Runtime Error

Solution code:
x,k,d = map(int,input().split())
c = abs(x)//d
if c < k:
    if (k-c) % 2 == 0:
        print(abs(x)%d)
    else:
        print(min(abs(abs(x)%d+d),abs(abs(x)%d-d)))
else:
    print(abs(x)-d*k)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
ans = -float('inf')
for i in range(N):
    piece = i
    temp = 0
    hoge = []
    key = 0
    for j in range(N):
        piece = P[piece-1]
        temp += C[piece-1]
        hoge.append(temp)
        if j+1 > K:
            key = 1
            break
        if piece == i:
            break
    if key == 1:
        ans = max(ans,max(hoge))
    elif hoge[-1]<=0:
        ans = max(ans,max(hoge))
    else:
        d = K//len(hoge)
        r = K%len(hoge)
        peak = max(hoge[-1]*(d-1)+max(hoge[r:]),hoge[-1]*d+max(hoge[:r]))
        ans = max(ans,peak)
print(ans)