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 = sys.stdin.readline


    
def inlt():
    return(list(map(int,input().split())))
    


n, k = inlt()
def greedy(C, path, val=0, i=1, cnt=1):
    val = val+C[path[i]]
    if cnt==k:
        return val    
    if i ==len(path)-1:
        i=-1     
    val = max(val, greedy(C, path, val, i+1, cnt+1))
    return val

def paths(P):
    all_paths = []
    max_val = float("-inf")
    for i in range(n):
        path = []
        j = P[i]
        path.append(i)
        while(j!=i):
            path.append(j)
            j = P[j]
        val = greedy(C, path, val=0, i=1, cnt=1)    
        if val>max_val:
            max_val = val
    return max_val    




P = inlt()
C = inlt()
P = [x-1 for x in P]
print(paths(P))

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=-10**18
flag=dict()
for i in range(n):
    if i in flag:
        continue
    cur=i
    accum=[]
    flag[cur]=0
    s=0
    while flag[cur]<2:
        cur=p[cur]-1
        s+=c[cur]
        accum.append(s)
        if cur not in flag:
            flag[cur]=0
        else:
            flag[cur]+=1
    l=len(accum)//2
    accum=[0]+accum
    for x in range(1,l+1):
        if accum[x+l-1]-accum[x-1]<=0:
            ans=max(ans,max(accum[x:x+min(k,l)])-accum[x-1])
        else:
            a=max(accum[x:x+l])-accum[x-1]
            b=max(accum[x:x+k%l])-accum[x-1]
            d=accum[x+l-1]-accum[x-1]
            ans=max(ans,max(k//l*d+b,max(k//l-1,0)*d+a))
print(ans)

Submission status: Runtime Error

Solution code:

import sys
input = sys.stdin.readline
def inlt():
    return(list(map(int,input().split())))
def paths(n, P):
    all_paths = []
    for i in range(n):
        path = []
        j = P[i]
        path.append(i)
        while(j!=i):
            path.append(j)
            j = P[j]
        all_paths.append(path)     
    return all_paths    
n, k = inlt()
def greedy(C, path, val=0, i=1, cnt=1):
    val = val+C[path[i]]
    if cnt==k:
        return val    
    if i ==len(path)-1:
        i=-1     
    val = max(val, greedy(C, path, val, i+1, cnt+1))
    return val

P = inlt()
C = inlt()
P = [x-1 for x in P]
all_paths = paths(n, P)
print(max([greedy(C, all_paths[i]) for i in range(n)]))

Submission status: Runtime Error

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

if n >= k:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        for j in range(k):
            now = p[now] - 1
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j] + c[now])
        ans = max(max(score), ans)
    print(ans)
else:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        check = [0] * n
        for j in range(k):
            go = p[now] - 1
            if check[go] == 1:
                break
            now = go
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j] + c[now])
            check[now] = 1
        d = k % j
        t = k // j
        score_2 = []
        for j in range(d):
            now = p[now] - 1
            if j == 0:
                score_2.append(c[now])
            else:
                score_2.append(score_2[j] + c[now])
        res = max(score)
        res_2 = score[-1] * t + max(score_2)
        ans = max(ans, res, res_2)

    print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import copy
from collections import deque

def get_part_sum_max(new_loop, n):
    loop = new_loop + new_loop
    cnt = 0
    max = 0
    for i in range(len(new_loop)):
        sum = 0
        for j in range(n):
            sum += new_loop[i+j]
        if max < sum:
            max = sum
    return max

def get_sum_max_roop(roop, c):
    sum = 0
    max = -1000000000000000000000
    for i in range(len(roop)):
        sum += c[i]
        if c[i] > max:
            max = c[i]
    return sum, max

def make_loop(loop, c):
    new_loop = []
    for i in loop:
        new_loop.append(c[i])
    return new_loop
        
        

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

    # ループを見つける
    jun01 = [0]*n
    junnum = [x for x in range(n)]
    roops = []
    while(junnum != []):
        start = junnum.pop()
        jun01[start] = 1
        now = start
        roop = [start]
        for i in range(n):
            next = p[now] - 1
            if next == start:
                roops.append(roop)
                break
            else:
                roop.append(next)
                jun01[next] = 1
                junnum.remove(next)
                now = next
    ans_max = -1000000000000000000000
    for roop in roops:
        new_loop = make_loop(roop, c)
        part_max = 0
        roop_sum, roop_max_value = sum(new_loop), max(new_loop)
        if roop_max_value <= 0:
            part_max = roop_max_value

        else:
            if k < n:
                nokori = k%n
                for i in range(1, nokori):
                    pmax = get_part_sum_max(new_loop, i)
                    if part_max < pmax:
                        part_max = pmax
            else:
                for i in range(1, n):
                    pmax = get_part_sum_max(new_loop, i)
                    if part_max < pmax:
                        part_max = pmax
                if roop_sum > 0:
                    ppart_max = 0
                    nokori = k%n
                    for i in range(1, nokori):
                        ppmax = get_part_sum_max(new_loop, i)
                        if ppart_max < pmax:
                            ppart_max = pmax
                    part_max += k//n*roop_sum -roop_sum
                    m1 = part_max + k//n*roop_sum -roop_sum
                    m2 = k//n*roop_sum + ppart_max
                    part_max = max(m1, m2)

        if part_max > ans_max:
            ans_max = part_max
    print(ans_max)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import copy
from collections import deque

def get_part_sum_max(new_loop, n):
    loop = new_loop + new_loop
    cnt = 0
    max = 0
    for i in range(len(new_loop)):
        sum = 0
        for j in range(n):
            sum += new_loop[i+j]
        if max < sum:
            max = sum
    return max

def get_sum_max_roop(roop, c):
    sum = 0
    max = -1000000000000000000000
    for i in range(len(roop)):
        sum += c[i]
        if c[i] > max:
            max = c[i]
    return sum, max

def make_loop(loop, c):
    new_loop = []
    for i in loop:
        new_loop.append(c[i])
    return new_loop
        
        

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

    # ループを見つける
    jun01 = [0]*n
    junnum = [x for x in range(n)]
    roops = []
    while(junnum != []):
        start = junnum.pop()
        jun01[start] = 1
        now = start
        roop = [start]
        for i in range(n):
            next = p[now] - 1
            if next == start:
                roops.append(roop)
                break
            else:
                roop.append(next)
                jun01[next] = 1
                junnum.remove(next)
                now = next
    ans_max = -1000000000000000000000
    print(roops)
    for roop in roops:
        new_loop = make_loop(roop, c)
        part_max = 0
        roop_sum, roop_max_value = sum(new_loop), max(new_loop)
        if roop_max_value <= 0:
            part_max = roop_max_value

        else:
            if k < n:
                nokori = k%n
                for i in range(1, nokori):
                    pmax = get_part_sum_max(new_loop, i)
                    if part_max < pmax:
                        part_max = pmax
            else:
                for i in range(1, n):
                    pmax = get_part_sum_max(new_loop, i)
                    if part_max < pmax:
                        part_max = pmax
                if roop_sum > 0:
                    ppart_max = 0
                    nokori = k%n
                    for i in range(1, nokori):
                        ppmax = get_part_sum_max(new_loop, i)
                        if ppart_max < pmax:
                            ppart_max = pmax
                    part_max += k//n*roop_sum -roop_sum
                    m1 = part_max + k//n*roop_sum -roop_sum
                    m2 = k//n*roop_sum + ppart_max
                    part_max = max(m1, m2)

        print(part_max)
        if part_max > ans_max:
            ans_max = part_max
    print(ans_max)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import random

IN = list(map(int, input().split()))
N, K = IN[0], IN[1]
P = list(map(int, input().split()))
C = [None] + list(map(int, input().split()))
#N = 45
#K = 10**8
#P = random.sample(range(1, N+1), k=N)
#C = [None] + random.choices(range(-10**8, 10**8), k=N)

verbose = False
g = {}
for i in range(1, N+1): g.update({i: P[i-1]})

def cumsum(a):
    tmp = [0]*(len(a)+1)
    for i in range(1, len(a)+1): tmp[i] = a[i-1] + tmp[i-1]
    return tmp[1:]

maxsc = -10**9-1
for i in range(1, N+1):
    if verbose: print('entering', i)
    pos = i
    cnt = 0
    steps, scores = [0]*(N+N+N), [0]*(N+N+N)
    path = set()
    while True:
        steps[cnt] = pos
        scores[cnt] = C[pos]
        pos = g[pos]
        cnt += 1
        if pos in steps: break # found closure
    if verbose: print('closure found')
    st = steps.index(pos) # start of closure
    if verbose: print('closure steps identified')
    closure_path = steps[st:cnt]
    closure_scores = scores[st:cnt]
    closure_score = sum(closure_scores)
    preclosure_len = st
    score_len = 0
    if verbose: print('closure path:', closure_path)
    closure_len = len(closure_path)
    cycles = (K-preclosure_len)//closure_len
    if cycles >= 1: cycles -= 1
    if cycles == 0:
        score_len = K
    else:
        score_len = preclosure_len + 1 + closure_len*cycles + resid
    resid = (K-preclosure_len)%closure_len
    if (cycles > 0):
        scores[cnt] = closure_score*cycles
        cnt+=1
    for j in range(K-preclosure_len-closure_len-closure_len*cycles):
        scores[cnt+j] = closure_scores[j%closure_len]
    if verbose: print('preclosure:', preclosure_len,
                      'cycles:', cycles, 'resid:', resid)
    if verbose: print(i, ':', scores)
    maxsc = max(max(cumsum(scores[0:score_len])), maxsc)
    if verbose: print(i, ': done, score_len:', score_len)


print(maxsc)

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(3000)
n, k = map(int, input().split())
pos = [int(i) for i in input().split()]
score = [int(i) for i in input().split()]
if max(score) <= 0:
  print(max(score))
else:
  pos = [0] + pos
  score = [0] + score
  max_point = -10 ** 11
  s_l = [[0]]
  nei = {}
  dic = {}
  loop = 0
  for i in range(1, n + 1):
    f_pos = i
    #print('f_pos',f_pos)
    if f_pos not in nei:
      points = [0]
      count = 0
      loop += 1
      while True:
        n_pos = pos[f_pos]
        points.append(points[-1] + score[n_pos])
        count += 1
        nei[f_pos] = [count, loop]
        if n_pos in nei:
          dic[loop] = count
          break
        f_pos = n_pos
      #print(nei)
      s_l.append(points)
      count = 1
    else:
      loop = nei[f_pos][1]
      count = nei[f_pos][0]
      points = s_l[loop]
    #print(points)
    #print(count)
    loop_num = dic[loop]
    s = points[count - 1]
    m = points[loop_num] - s
    a = k // loop_num
    b = k % loop_num
    if points[loop_num] > 0:
      point = points[loop_num] * a
      if point > max_point and a != 0:
        max_point = point
    else:
      point = 0
      if a > 0:
        b = loop_num
    #print(point)
    if b > 0:
      t_max = -10 ** 11
      if loop_num - count + 1 >= b:
        for j in range(b):
          t = points[j + count] - s
          #print(t)
          if t > t_max:
            t_max = t
      else:
        for j in range(count, loop_num + 1):
          t = points[j] - s
          #print(t)
          if t > t_max:
            t_max = t
        for j in range(1, b - loop_num + count):
          t = points[j] + m
          #print(t)
          if t > t_max:
            t_max = t
      point += t_max
    #print(point)
    if point > max_point:
      max_point = point
  print(max_point)

Submission status: Runtime Error

Solution code:
import bisect
import collections
import copy
import functools
import heapq
import math
import sys
from collections import deque
from collections import defaultdict
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
MOD = 10**9+7

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

sumlist1 = [[0]*N for _ in range(N)]
walist = [[0]*N for _ in range(N)]
loopcount = [0]*N

for h in range(N):
    sumlist1[h][0] = C[h]
    walist[h][0] = C[h]
    now = h
    l = 0
    for i in range(1,N):
        now = P[now]-1

        if sumlist1[h][i-1] < 0:
            sumlist1[h][i] = C[now]
        else:
            sumlist1[h][i] += sumlist1[h][i-1] + C[now]
        walist[h][i] += walist[h][i-1] + C[now]
        
        l += 1
        if now == h:
            break
    else:
        l += 1
    loopcount[h] = l
#print(sumlist1)

maxlist = [0]*N
for i in range(N):
    T = loopcount[i]
    wa = walist[i][T-1]
    #print(wa)

    loop = K//T
    amari = K%T

    if wa >= 0:
        if loop == 0:
            if amari != 0:
                maxlist[i] = wa*loop + max(sumlist1[i][:amari])
            else:
                maxlist[i] = max(sumlist1[i][:amari])
        else:
            if amari != 0:
                maxlist[i] = max(wa*loop + max(sumlist1[i][:amari]), wa*(loop-1) + max(sumlist1[i]))
            else:
                maxlist[i] = max(wa*loop, wa*(loop-1) + max(sumlist1[i]))
                a = 5//0
            

    else:
        if loop == 0:
            maxlist[i] = max(sumlist1[i][:amari])
        else:
            maxlist[i] = max(sumlist1[i])

print(max(maxlist))
#print(sumlist1)

Submission status: Runtime Error

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

if n >= k:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        for j in range(k):
            now = p[now] - 1
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
        ans = max(max(score), ans)
else:
    ans = -float('inf')
    for i in range(n):
        now = i
        score = []
        check = [0] * n
        cnt = 0
        for j in range(k):
            go = p[now] - 1
            if check[go] == 1:
                break
            now = go
            if j == 0:
                score.append(c[now])
            else:
                score.append(score[j-1] + c[now])
            check[now] = 1
            cnt += 1

        if score[-1] >= 0:
            d = k // cnt
            e = k % cnt
            res = score[-1] * d
            score = []
            for j in range(e):
                now = p[now] - 1
                if j == 0:
                    score.append(c[now])
                else:
                    score.append(score[j-1] + c[now])
            res += max(score)
        else:
            res = max(score)
        ans = max(ans, res)
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()))

sumlist1 = [[0]*N for _ in range(N)]
walist = [[0]*N for _ in range(N)]
loopcount = [0]*N

for h in range(N):
    sumlist1[h][0] = C[h]
    walist[h][0] = C[h]
    now = h
    l = 0
    for i in range(1,N):
        now = P[now]-1

        if sumlist1[h][i-1] < 0:
            sumlist1[h][i] = C[now]
        else:
            sumlist1[h][i] += sumlist1[h][i-1] + C[now]
        walist[h][i] += walist[h][i-1] + C[now]
        
        l += 1
        if now == h:
            break
    else:
        l += 1
    loopcount[h] = l
#print(sumlist1)

maxlist = [0]*N
for i in range(N):
    T = loopcount[i]
    wa = walist[i][T-1]
    #print(wa)

    loop = K//T
    amari = K%T

    if wa >= 0:
        if loop == 0:
            if amari != 0:
                maxlist[i] = wa*loop + max(sumlist1[i][:amari])
            else:
                maxlist[i] = max(sumlist1[i][:amari])
        else:
            if amari != 0:
                maxlist[i] = max(wa*loop + max(sumlist1[i][:amari]), wa*(loop-1) + max(sumlist1[i]))
            else:
                maxlist[i] = max(wa*loop, wa*(loop-1) + max(sumlist1[i]))
            

    else:
        if loop == 0:
            maxlist[i] = max(sumlist1[i][:amari])
        else:
            maxlist[i] = max(sumlist1[i])

print(max(maxlist))
print(sumlist1)

Submission status: Runtime Error

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

    max_score = -10**100

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

    print(max_score)

if __name__ == "__main__":
    execute()

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> VI;
typedef vector<vector<int>> VVI;
typedef vector<ll> VLL;
typedef vector<vector<ll>> VVLL;
typedef pair<ll, ll> Pair;
template <class T> T input() {T t; cin>>t; return t;}
#define FOR(i,a,b) for (ll i = a; i < b; i++)
#define REP(i,b) FOR(i,0,b)
#define RFOR(i,a,b) for (ll i = a-1; i >= b; i--)
#define RREP(i,a) RFOR(i,a,0)
#define REPALL(i,x) for (ll i = 0; i < x.size(); i++)
#define RREPALL(i,x) for (ll i = x.size()-1; i >= 0; i--)
#define REPITR(itr,x) for (auto itr = (x).begin(); itr != (x).end(); itr++)
#define ALL(x) (x).begin(), (x).end()
#define SORT(x) sort(ALL(x))
#define MIN_ELEMENT(x) min_element(ALL(x))
#define MAX_ELEMENT(x) max_element(ALL(x))
#define COUNT(x,num) count(ALL(x), num)
#define MEMSET(x,val) memset(x, val, sizeof(x))
#define CHMAX(a,b) a = max(a,b)
#define CHMIN(a,b) a = min(a,b)
#define FIND(x,key) x.find(key) != x.end()
#define IN_RANGE_V2(v,k,x,y) (0<=x+dx[k]&&x+dx[k]<v[y].size()&&0<=y+dy[k]&&y+dy[k]<v.size())
#define debug(x) cerr<<__LINE__<<": "<<(#x)<<" = "<<(x)<<endl;
void YES(bool flag) {cout<<(flag ? "YES" : "NO")<<endl;}
void Yes(bool flag) {cout<<(flag ? "Yes" : "No")<<endl;}
void yes(bool flag) {cout<<(flag ? "yes" : "no")<<endl;}
#define PRINT_ARRAY_H(a) REPALL(__i,a) {cout<<a[__i]<<(__i != a.size()-1 ? " " : "");} newline;
#define PRINT_ARRAY_V(a) REPALL(__i,a) {cout<<a[__i]<<endl;}
#define e1 first
#define e2 second
#define newline putchar('\n')
#define cspace ' '
#define sspace " "
const int INF = 1e7;
const ll MOD = 1e9 + 7;
const double pi = 3.141592653589793;
const VI dx = {1, 0, -1, 0};
const VI dy = {0, 1, 0, -1};
//const VI dx = {1, 1, 0, -1, -1, -1, 0, 1};
//const VI dy = {0, 1, 1, 1, 0, -1, -1, -1};

ll n, k;
VLL p, c;
VLL dp_score(5005);
VLL dp_cycle(5005);
VLL dp_max(5005);

void set_dp(ll idx)
{
    ll tscore = 0ll;
    ll tidx = idx;
    ll cnt = 0ll;
    REP(i,n) {
        cnt++;
        tscore += c[p[tidx]];
        CHMAX(dp_max[idx], tscore);
        if (p[tidx] == idx) {
            break;
        } else {
            tidx = p[tidx];
        }
    }
    dp_score[idx] = tscore;
    dp_cycle[idx] = cnt;
}

ll get_score(ll idx)
{
    ll tidx = p[idx];
    ll tans = c[tidx];
    ll tk = k-1;
    //cout<<idx<<": "<<endl;
    while (tk > 0) {
        if (tk < dp_cycle[tidx]) {
            ll tscore = tans;
            REP(i,tk) {
                tscore += c[p[tidx]];
                CHMAX(tans, tscore);
                tidx = p[tidx];
            }
            tk = 0;
        } else if (dp_score[idx] > 0) {
            ll tmp = tk / dp_cycle[tidx];
            tans += tmp * dp_score[tidx];
            tk -= tmp * dp_cycle[tidx];
        } else {
            tans += dp_max[tidx];
            tk = 0;
        }
        //cout<<tk<<sspace<<tans<<endl;
    }
    return tans;
}

void solve()
{
    ll ans = -(ll)(1e18) -1;
    cin>>n>>k;
    p.resize(n); c.resize(n);
    REP(i,n) {cin>>p[i]; p[i]--;}
    REP(i,n) {cin>>c[i];}
    REP(i,n) {
        set_dp(i);
        //cout<<i<<"->"<<dp_score[i]<<sspace<<dp_cycle[i]<<endl;
    }
    REP(i,n) {
        CHMAX(ans, get_score(i));
    }
    cout<<ans<<endl;
}

int main()
{
    cout<<fixed<<setprecision(20);
    int __t = 1;
    //cin>>__t;
    REP(i,__t) {
        solve();
    }
    return 0;
}

Submission status: Runtime Error

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

ls_score = []

for i in range(1,N+1): #iはスタート位置
    a = i
    score = 0
    ls_route = []
    ls_s = [0]
    for j in range(K):
        if a in ls_route:
            S = ls_route.index(a)
            G = len(ls_route) - 1
            p = (K - S) % (G - S + 1) #ループの終わりの位置
            q = (K - S) // (G - S + 1) #ループの数
            score_roup = ls_s[G+1] - ls_s[S]
            M = max(ls_s[S+1:S+p+1])
            ls_score.append(max([score_roup * q + M, max(ls_s[1:len(ls_s)])]))
            break
        else:
            ls_route.append(a)
            b = ls_P[a]
            score += ls_C[b]
            a = b
            ls_s.append(score)
    else:
        ls_score.append(max(ls_s[1:len(ls_s)]))
print(max(ls_score))

Submission status: Runtime Error

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

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(gone)
#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])
        rem=k%len(maxpoints[i])
        temp=points[i]*times
        if rem!=0:
            temp+=maxpoints[i][rem-1]
    ans=max(temp,ans)
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
for i in range(N):
    P[i] -= 1
C = list(map(int, input().split()))
 
ans = -(10 ** 18)
 
for si in range(N):
    x = si
    loop = []
    total = 0
    while 1:
        x = P[x]
        loop.append(C[x])
        total += C[x]
        if x == si:
            break
    T = len(loop)  
    tmp = 0
    for i in range(T):
        tmp += loop[i]
        if K < i + 1:
            break
        now = tmp
        if total > 0:  
            loop_times = (K - (i + 1)) // T  
            now += total * loop_times
        ans = max(ans, now)
 
print(ans)
 
N, K = map(int, input().split())
P = list(map(int, input().split()))
for i in range(N):
    P[i] -= 1
C = list(map(int, input().split()))

ans = -(10 ** 18)

for si in range(N):
    x = si
    loop = []
    total = 0
    while 1:
        x = P[x]
        loop.append(C[x])
        total += C[x]
        if x == si:
            break
    T = len(loop) 
    tmp = 0
    for i in range(T):
        tmp += loop[i]
        if K < i + 1:
            break
        now = tmp
        if total > 0: 
            loop_times = (K - (i + 1)) // T 
            now += total * loop_times
        ans = max(ans, now)

print(ans)

Submission status: Runtime Error

Solution code:
class UnionFind():
    n=1
    par=[0]
    rnk=[0]
    def __init__(self,size):
        self.n=size
        self.par=[i for i in range(self.n)]
        self.rnk=[0 for i in range(self.n)]
    def find(self,vertex1):
        if self.par[vertex1]==vertex1:
            return vertex1
        else:
            self.par[vertex1]=self.find(self.par[vertex1])
            return self.par[vertex1]
    def unite(self,vertex1,vertex2):
        vertex1=self.find(vertex1)
        vertex2=self.find(vertex2)
        if vertex1==vertex2:
            return
        if (self.rnk[vertex1]<self.rnk[vertex2]):
            self.par[vertex1]=vertex2
        else:
            self.par[vertex2]=vertex1
            if(self.rnk[vertex1]==self.rnk[vertex2]):
                self.rnk[vertex1]+=1
    def same(self,vetrex1,vertex2):
        return self.find(vetrex1)==self.find(vertex2)

N,K=map(int,input().split())
P=[int(i)-1 for i in input().split()]
Q=[P[i] for i in range(N)]
C=[int(i) for i in input().split()]
D=dict()
G=UnionFind(N)
for i in range(N):
    G.unite(i,P[i])
for i in range(N):
    if G.find(i) in D:
        D[G.find(i)]+=1
    else:
        D[G.find(i)]=1
dp=[[0 for j in range(N)] for i in range(N+1)]
#i->P[i]
#jからスタートしたときにi番目に獲得する得点
for i in range(N):
    #Q=P^{i+1}
    for j in range(N):
        dp[i+1][Q[j]]=dp[i][P[Q[j]]]+C[P[Q[j]]]
    Q=[P[Q[i]] for i in range(N)]

#for line in dp:
#    print(line)

cycle=[D[G.find(i)] for i in range(N)]
def maxpoint(i,k):
    if k<=N:
        return max([dp[j][i] for j in range(1,k+1)])
    elif dp[cycle[i]][i]>0:
        return maxpoint(i,k%cycle[i])+dp[cycle[i]][i]*(k//cycle[i])
    else:
        return maxpoint(i,N)
print(max([maxpoint(i,K) for i in range(N)]))
#print([maxpoint(i,K) for i in range(N)])

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

ans = c[1]

for i in range(1,N+1):
    naw = i
    S = 0
    l = 0
    lmax = c[1]
    kl = K

    while 1:
        naw = p[naw]
        S += c[naw]
        l += 1
        kl -= 17
        if S > lmax:
            lmax = S
            max_l = l
        if kl == 0 or naw == i:
            break
    
    if kl == 0:
        imax = lmax
    else:
        if S <= 0:
            imax = lmax
        else:
            imax = lmax + S * ( (K - max_l) // l)
    
    if (imax > ans):
        ans = imax

print(ans)

Submission status: Runtime Error

Solution code:
from numba import njit, b1, i4, i8, f8


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

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

    print(ans)

resolve()

Submission status: 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 = c[1]

for i in range(1,N+1):
    naw = i
    S = 0
    l = 0
    lmax = c[1]
    kl = K

    while 1:
        naw = p[naw]
        S += c[naw]
        l += 1
        kl -= 17
        if S > lmax:
            lmax = S
            max_l = l
        if kl == 0 or naw == i:
            break
    
    if kl == 0:
        imax = lmax
    else:
        if S <= 0:
            imax = lmax
        else:
            imax = lmax + S * ( (K - max_l) // l)
    
    if (imax > max):
        max = imax

print(max)

Submission status: Runtime Error

Solution code:
from numba import jit


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

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

    print(ans)

resolve()