Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Time Limit Exceeded

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

maxsc = -1*10**9
init = True
for i in range(1, N+1):
    pos, score = i, 0
    for st in range(K):
        score += C[pos-1]
        pos = P[pos-1]
        maxsc = max(maxsc, score)
print (maxsc)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import numpy as np

input = sys.stdin.readline


def S():
    return input().rstrip()


def I():
    return int(input())


def MI():
    return map(int, input().split())


n, k = MI()
p = list(MI())
c = list(MI())

p.insert(0, 0)
c.insert(0, 0)

idx = np.array(range(n + 1))
loop = list()
ans = -(10 ** 9)
for i in range(1, n + 1):
    # passed = np.full(n + 1, -1)
    # passed[i] = 0
    score = 0
    next = i
    for j in range(1, k + 1):
        next = p[next]
        # if passed[next] >= 0:
        #     loop.append(set(idx[passed > passed[next]]))
        #     break
        # else:
        #     passed[next] = j
        score += c[next]
        ans = max(ans, score)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,K=list(map(int,input().split()))
P=list(map(int,input().split()))
C=list(map(int,input().split()))
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()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

Q=[]
uf=UnionFind(N)
for i in range(N):
    uf.union(i,P[i]-1)
D1=list(uf.all_group_members().values())
D2=[]
for i in D1:
    ans=0
    for j in i:
        ans+=C[j]
    D2.append(ans)
L=[len(i) for i in D1]
S=min(2*max(L),K)

for i in range(N):
    ans=-float('inf')
    ans1=0
    now=P[i]-1
    for j in range(S):
        ans1+=C[now]
        now=P[now]-1
        ans=max(ans1,ans)
    Q.append(ans)

Q2=[]
for i,value in enumerate(D2):
    if value>0:
        ans3=value*(K//L[i])
        for j in D1[i]:
            ans=-float('inf')
            ans1=0
            now=P[j]-1
            for k in range(K%L[i]):
                ans1+=C[now]
                now=P[now]-1
                ans=max(ans1,ans)
            Q.append(ans3+ans)
print(max(Q))

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
M = -10**9

for i in range(n):
    cnt = 0
    mv = i
    for j in range(k):
        mv = p[mv]-1
        cnt += c[mv]
        M = max(M, cnt)
print(M)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
# モジュールのインポート
import sys

# 標準入力を取得
N, K = list(map(int, input().split()))
P = list(map(int, input().split()))
C = list(map(int, input().split()))

# 求解処理
ans = -sys.maxsize
for i in range(N):
    pos = i
    S = []
    score = 0
    while True:
        pos = P[pos] - 1
        score += C[pos]
        S.append(score)
        if pos == i:
            break
    length = len(S)

    if K <= length:
        ans = max(ans, max(S[:K]))
    else:
        circ_S = S[-1]
        circ_cnt = int(K / length)
        if circ_S > 0:
            if K % length == 0:
                ans = max(ans, (circ_cnt - 1) * circ_S + max(S))
            else:
                ans = max(ans, circ_cnt * circ_S + max(S[:(K % length)]))
        else:
            ans = max(ans, max(S))

# 結果出力
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = 0
d = deque()
max_res = -float("inf")
for start in range(n):
    d.append(start)
    count = 0
    res = 0
    while count < k:
        now = d.pop()
        next = p[now]
        d.append(next-1)
        res += c[next-1]
        max_res = max(res, max_res)
        count += 1
print(max_res)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
se=[0 for i in range(n)]
re=[]
for i in range(n):
    if se[i]==0:
        a=[]
        st=i
        while True:
            a.append(c[st])
            if p[st]-1!=i:
                st=p[st]-1
                se[st]=1
            else:
                break
        re.append(a)
ma=-float("inf")
for i in range(len(re)):
    ma2=0
    if k%len(re[i])==0:
        ma2=sum(re[i])*(k//len(re[i]))
        re2=re[i]+re[i]
        for j in range(1,len(re[i])):
            for m in range(0,len(re[i])):
                ma2=max(ma2,sum(re2[m:m+j]))
    else:
        if sum(re[i])>=0:
            ma2+=sum(re[i])*(k//len(re[i]))
        bi=k%len(re[i])
        ma1=-float("inf")
        re1=re[i]+re[i]
        for j in range(1,bi+1):
            for m in range(0,len(re[i])):
                ma1=max(ma1,sum(re1[m:m+j]))
        ma2+=ma1
    ma=max(ma,ma2)
print(ma)

Submission status: Time Limit Exceeded

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

P = [p-1 for p in P]
#print(P)

visited = set()
ans = 0
for i in range(N):
  if i in visited:
    continue
  tmp = []
  j = i
  while j not in visited:
    tmp.append(C[j])
    visited.add(j)
    j = P[j]
  #print(tmp,visited)  
  M = len(tmp)
  L = max(0,sum(tmp))
  now = L * (K // M)
  k = K % M
  tmp2 = 0
  tmp4 = 0
  for l in range(1,min(M,K)+1):
    tmp2 += tmp[l-1]
    tmp3 = tmp2
    for j in range(M):
      tmp4 = max(tmp4, tmp3) 
      tmp3 += tmp[(j+l)%M] - tmp[j%M]
      #print(tmp4, l, j)
      ans = max(ans, now+tmp4 if l <= k else now+tmp4-L)
  #ans = max(ans, now+tmp4 if l <= k else now+tmp4-L) 
  #print(i, L, now, l, k, tmp4, M, visited, now+tmp4)
  del tmp

flag = True
for c in C:
  if c > 0:
    flag = False
    
print(max(C) if flag else ans)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
p = [int(pn) for pn in input().split()]
c = [int(cn) for cn in input().split()]
scores = []
for i in range(n):
  genzai = p[i] - 1
  score = c[genzai]
  scores.append(score)
  for _ in range(k-1):
    genzai = p[genzai] - 1
    score += c[genzai]
    scores.append(score)
print(max(scores))

Submission status: Time Limit Exceeded

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

score = [0 for i in range(n)]
position = [i for i in range(n)]

max_i=max(list_c)
for i in range(k):
    for j in range(n):
        position[j]=list_p[position[j]]-1
        score[j]+=list_c[position[j]]
    max_re=max(score)
    if max_re > max_i:
        max_i = max_re
print(max_i)

Submission status: Time Limit Exceeded

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

ans = -float("INF")
for i in range(n):
    pi = p[i]
    x = c[pi-1]
    a = x
    for j in range(k-1):
        pi = p[pi-1]
        a = max(a,x+c[pi-1])
        x += c[pi-1]
    ans = max(ans,a)
print(ans)

Submission status: Time Limit Exceeded

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

ans = []
for i in range(1, n + 1):
    visited = [False] * (n + 1)
    move = k
    point = 0
    loop = 0
    loop_point = 0
    now = i
    visited[i] = True

    while move > 0:
        move -= 1
        now = p[now]
        point += c[now]
        loop += 1
        loop_point += c[now]
        ans.append(point)
        if visited[now]:
            point += loop_point * (move // loop)
            ans.append(point)
            move %= loop
            visited = [False] * (n + 1)
            loop_point = 0
        else:
            visited[now] = True

print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
def main():
    n,k=map(int,input().split())
    p=list(map(lambda x:int(x)-1,input().split()))
    c=list(map(int,input().split()))
    ans = -10**9-1
    for i in range(n):
        now = i
        score = [0]
        e = set()
        for j in range(k):
            if p[now] in e:
                if score[-1] < 0:
                    break
                else:
                    nokori = k-j
                    if nokori >= j:
                        add = score[-1]*(nokori//j)
                        score += [x+add for x in score[1:]]
                        nokori %= j
                    #print("loop;", score, "nokori:", nokori)
                    for _ in range(nokori):
                        now = p[now]
                        score.append(score[-1]+c[now])
                        #print("now:",now,score)
                    break
            else:
                now = p[now]
                e.add(now)
                score.append(score[-1]+c[now])
                #print("k=%s, now:%s"%(j+1,now),score)
        ans = max(ans, *(score[1:]))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
ans = -float('inf')
for n in range(N):
    ans_pre = 0
    for _ in range(K):
        index = P[n] - 1
        ans_pre += C[index]
        n = index
        ans = max(ans, ans_pre)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, k = map(int, input().split())
pp = input().split()
cc = input().split()
npp=np.array(pp, dtype=int)
ncc=np.array(cc, dtype=int)

pointmax=-1E9
nmax=n

for istart in range(0,n):
  point=0
  loc=istart
  k_pointmax=-1E9
  k_pointmax2=-1E9
  for ik in range(1,k+1):
    loc=npp[loc]-1
    point+=ncc[loc]
    if (point >= k_pointmax): k_pointmax=point 

    if ((ik % nmax) == 0): 
      if (k_pointmax2 == k_pointmax): 
        break
      else:
        k_pointmax2=k_pointmax
      
  if (k_pointmax >= pointmax): pointmax=k_pointmax

print(pointmax)

Submission status: Time Limit Exceeded

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

ans=-float('inf')

v_score={}

def get_loop_score(start): # return loop len and its loop score
    if start in v_score:
        return v_score[start]

    now_p=0
    visited=set()
    nxt=p[start]-1

    while True:
        nxt=p[nxt]-1
        if nxt in visited:
            break
        visited.add(nxt)
        now_p+=c[nxt]

    for v in visited:
        v_score[v]=now_p
    return now_p
def simulate(start,nokori): # ret max possible score
    now_p=0
    nxt=p[start]-1
    cnt=0
    p_lis=[]

    while True:
        nxt=p[nxt]-1
        visited.add(nxt)
        now_p+=c[nxt]
        p_lis.append(now_p)
        cnt+=1
        if cnt==nokori:
            break

    return max(p_lis)
for i in range(n):
    p_lis=[]

    cnt=0
    now_p=0
    nxt=p[i]-1

    visited=set()

    while True:
        now_p+=c[nxt]
        nxt=p[nxt]-1
        p_lis.append(now_p)

        cnt+=1
        if cnt==k:
            break

        if k>5010 and nxt in visited:
            break
        visited.add(nxt)

    if cnt!=k: # loop detected
        nokori = k-cnt
        loop_score=get_loop_score(nxt)
        if loop_score <= 0: # no loop
            nokori=len(visited)
        else: # loop as much as possible
            loops = nokori//len(visited) - 1
            now_p+= loops*loop_score
            nokori = loops*len(visited)

        score = simulate(nxt,nokori)
        p_lis.append(score)

    ans=max(ans,max(p_lis))

print(ans)

Submission status: Time Limit Exceeded

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

ans=C[0]
for n in range(N):
	c=0
	i=n
	for k in range(K):
		i=P[i]-1
		c+=C[i]
		ans=max(ans,c)
	
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

line = [int(i) for i in input().rstrip().split()]
N = line[0]
K = line[1]
P = [int(i) for i in input().rstrip().split()]
C = [int(i) for i in input().rstrip().split()]

score = 0
S = []

for i in range(N):
  x = i
  for j in range(K):
    x = P[x]-1
    score += C[x]
    S.append(score)
  score = 0
  
S = np.array(S)
print(np.max(S))

Submission status: Time Limit Exceeded

Solution code:
from copy import copy
n, k = map(int, input().split())
p = list(map(int,input().split()))
c = list(map(int, input().split()))
di = {}
for i in range(n):
    di[i+1] = False
l = 1
cc = 0
per = [] # ループの順番
while cc < n:
    tmp = []
    while True:
        if di[l]:
            break
        else:
            tmp.append(l)
            di[l] = True
            cc += 1
            l = p[l-1]
    per.append(tmp)
    for i in range(n):
        if not di[i+1]:
            l = p[i]
#print(per)
dd = {} # 何個目のループに属するか
for i in range(n):
    dd[i+1] = 0
for i in range(len(per)):
    for j in per[i]:
        dd[j] = i
#print(dd)
su = [] # ループ１週の和
for i in range(len(per)):
    tmp = 0
    for j in per[i]:
        tmp += c[j-1]
    su.append(tmp)
#print(su)
s2 = [] # ループ１週何個か
for i in range(len(per)):
    s2.append(len(per[i]))
#print(s2)
ans = -1*(10**10)
#d2 = {} # per[dd]の中でなんばんめにあるか(0インデックス)
#for i in range(len(per)):
#    for j in range(len(per[i])):
#        d2[per[i][j]] = j
#print(d2)
for i in range(n):
    loop = dd[i+1]
    w = i+1
    kk = copy(k)
    if k < s2[loop]:
        tmp = 0
        m = -10**9
        for j in range(k):
            w = p[w-1]
            tmp += c[w-1]
            m = max(m, tmp)
        ans = max(ans, m)
    else:
        if su[loop] <= 0:
            tmp = 0
            m = -10**9
            for j in range(k):
                w = p[w-1]
                tmp += c[w-1]
                m = max(m, tmp)
            ans = max(ans, m)
        else:
            m_loop = kk // (s2[loop])
            m_loop -= 1
            kk -= m_loop * s2[loop]
            tmp = su[loop]*m_loop
            m = -10**9
            for j in range(kk):
                w = p[w-1]
                tmp += c[w-1]
                if c[w-1] <= 0:
                  continue
                m = max(m, tmp)
            ans = max(ans, m)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, K = (int(x) for x in input().split())
P = []
C = []
P = list(map(int, input().split()))
C = list(map(int, input().split()))
Sum = 0
Max = C[0]
for i in range(N):
    Sum += C[i]
if K < N:
    for i in range(N):
        p = i
        x = 0
        s = 0
        while x < K:
            p = P[p] - 1
            s += C[p]
            x += 1
            Max = max(Max, s)
elif Sum < 0:
    for i in range(N):
        p = i
        x = 0
        s = 0
        while x < N:
            p = P[p] - 1
            s += C[p]
            x += 1
            Max = max(Max, s)
else:
    for i in range(N):
        p = i
        x = 0
        s = 0
        while x < K:
            p = P[p] - 1
            s += C[p]
            x += 1
            Max = max(Max, s)
print(Max)

Submission status: Time Limit Exceeded

Solution code:

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

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

max_val = -float('inf')
for i in range(N):
    now_i = i
    val = 0
    for j in range(K):
        next_i = P[now_i] - 1
        val += C[next_i]
        now_i = next_i
        
        if max_val < val:
            max_val = val
print(max_val)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
max_point = -float('inf')
for i in range(1, n+1):
  point = 0
  cur = i
  for j in range(k):
    cur = p[cur-1]
    point += c[cur-1]
    max_point = max(max_point, point)
print(max_point)

Submission status: Time Limit Exceeded

Solution code:
#d
n,k = map(int,input().split())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
newlist = [0 for i in range(k)]
maxlist = []


for i in range(n):
    score = 0
    Max = float("-inf")
    num1 = i
    num2 = 0
    for j in range(k):
        newlist[j] = p[num1-1]
        num1 = p[num1-1]
    for j in newlist:
        score += c[j-1]
        if Max < score :
            Max = score
    maxlist.append(Max)
        
print(max(maxlist))

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Cs = list(map(int, input().split()))

# print(N, K)
# print(Ps)
# print(Cs)


result = -1000000000

for i in range(N):
  score = 0
  # print(i)
  now = i
  for k in range(K + 1):
    if k != 0:
      now = Ps[now] - 1
      # print("now" + str(now))
      score += Cs[now]
      # print(i, k, score)
      if score >= result:
        result = score

print(result)

Submission status: Time Limit Exceeded

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

ans = min(C)
for i in range(N) :
    log = [i+1]
    t = 0
    b = 0
    a = i+1
    while len(log) == len(set(log)) :
        b += C[P[a-1]-1]
        ans = max(ans,b)
        t += 1
        log.append(P[a-1])
        a = P[a-1]
        if t == K :
            break
    if b >= 1  :
       d = K%t
       e = K//t
       f = b*e
       for _ in range(d) :
           f += C[P[a-1]-1]
           a = P[a-1]
       ans = max(ans,f)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int,input().split())
p = [0] + list(map(int,input().split()))
c = [0] + list(map(int,input().split()))
ans = max(c[1:])
t = 0
for i in range(1,n+1):
    # print(ans)
    j = p[i]
    temp = c[i]
    cnt = 1
    ans = max(ans,temp)
    tempans = 0
    while i!=j:
        
        temp += c[j]
        j = p[j]
        cnt += 1
        # if i==5:
        #     print(j,c[j],temp)
    t = cnt
    tt = ans
    # if i==8:
    #     print(temp,t)
    if t < k:
        if temp > 0:
            # print(k,t,i)
            tempans += temp*(k//t - 1)
            tt = tempans
            j = p[i]
            for l in range(k-(k//t - 1)*t):
                tempans += c[j]
                j = p[j]
                tt = max(tt,tempans)
            ans = max(ans,tt)
            # print(ans)
        else:
            j = p[i]
            for l in range(k):
                tempans += c[j]
                j = p[j]
                tt = max(tt,tempans)
            ans = max(ans,tt)
            # print(ans)
    else:
        j = p[i]
        for l in range(k):
            tempans += c[j]
            j = p[j]
            tt = max(tt,tempans)
        ans = max(ans,tt)
        # print(ans)
    # if ans == 29779631210:
    #     print(i,ans,t,temp)
    #     exit()
print(ans)

Submission status: Time Limit Exceeded

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

ans = -((10)**10)

for sp in range(N):
    if K <= N:
        # 愚直にやる
        nextp = P[sp]
        score = C[sp]
        ans = max(ans, score)
        rest = K - 1
        while rest > 0:
            score += C[nextp]
            nextp = P[nextp]
            ans = max(ans, score)
            rest -= 1
    else:
        
        # K の方がNより大きい
        cache = set([sp])
        nextp = P[sp]
        score = C[sp]
        l = 1
        ans = max(ans, score)

        while not nextp in cache:
            cache.add(nextp)
            score += C[nextp]
            nextp = P[nextp]
            ans = max(ans, score)
            l += 1
        
        # print("l:", l)
        # print("sc:", score)
        rest = 0
        if K >= l:
            loop = K // l
            score *= loop
            ans = max(ans, score)
            rest = K - (l*loop)
        
        if rest > 0:
            nextp2 = P[sp]
            score += C[sp]
            rest -= 1
            ans = max(ans, score)

            while rest > 0:
                score += C[nextp2]
                nextp2 = P[nextp2]
                rest -= 1
                ans = max(ans, score)
        
            # score += rscore

        # ans = max(score, ans)
        # print("sp: ", sp, score)

print(ans)

Submission status: Time Limit Exceeded

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


def start_game(cursor_masu):
    # initialize
    visit_count = [0 for _ in range(N + 1)]
    point = 0
    points = list()

    # move
    for _ in range(K):
        cursor_masu = masues[cursor_masu]
        if visit_count[cursor_masu] >= 1 and point < 0:
            break

        point += masu_points[cursor_masu]
        points.append(point)

        visit_count[cursor_masu] += 1

    return points


result = list()
for i in range(1, N + 1):
    result += start_game(i)
print(max(result))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
#from itertools import accumulate
#from itertools import combinations
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

#N,K = 4,4
#P = [2,3,4,1]
#C = [-9,9,1,-1]

visited = [False]*(N+1)
loops = []
for v in range(1,N+1):
    if visited[v]:
        continue
    l = [v]
    while True:
        v = l[-1]
        visited[v] = True
        nv = P[v-1]
        if visited[nv]:
            break
        l.append(nv)
    loops.append(l)

cand = []
for loop in loops:
    temp = 0
    vals = [C[i-1] for i in loop]
    l = len(vals)
    vals2 = vals+vals[:-1]
    vals3 = vals+vals+vals[:-1]
    cumsum = [0]
    for v in vals3:
        cumsum.append(cumsum[-1] + v)
    #cumsum = [0] + list(accumulate(vals2))
    gh = []
    #print(vals)
    if K <= l:
        temp = 0
        for left in range(0,2*l-K):
            for right in range(left+1,left+K+1):
                gh.append(cumsum[right] - cumsum[left])
        if gh:
            temp = max(gh)
    else:
        temp = 0
        s = sum(vals)
        q, r = divmod(K,l)
        q -= 1
        r += l
        for left in range(0,3*l-r):
            for right in range(left+1,left+r+1):
                #print(left,right)
                gh.append(cumsum[right] - cumsum[left])
        if gh:
            temp = max(gh)
        if s > 0:
            temp += q * s
    cand.append(temp)
print(max(cand))

Submission status: Time Limit Exceeded

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

mx = [0] * N
cnts = [0] * N
for i in range(N):
  if mx[i] == 0:
    nxt = P[i]-1
    tmp = 0
    l = [nxt]
    for j in range(N):
      tmp += C[nxt]
      nxt = P[nxt]-1
      l.append(nxt)
      if nxt == i:
        tmp += C[nxt]
        cnt = j+2
        break
    for k in l:
      cnts[k] = cnt
      n = ((K//cnt)-1) * tmp
      if tmp > 0:
        mx[k] += n
    
for i in range(N):
  nxt = P[i]-1
  tmp = 0
  m = min(C) - 1
  for j in range((K%cnts[i])+cnts[i]):
    tmp += C[nxt]
    m = max(m, tmp)
    nxt = P[nxt]-1
  mx[i] += m

ans = max(mx)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
*p,=map(int,input().split())
*c,=map(int,input().split())
score_max=-10**9-1
for i in range(n):
    score=0
    next=p[i]
    for j in range(k):
        score+=c[next-1]
        next=p[next-1]
        score_max=max(score,score_max)
print(score_max)

Submission status: Time Limit Exceeded

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

if max(c) < 0:
    print(max(c))
    exit()

ans = 0
for i in range(n):
    score = 0
    prev = i
    for j in range(min(n, k)):
        score += c[p[prev]-1]
        prev = p[prev]-1
        ans = max(ans, score)
if k <= n:
    print(ans)
    exit()

else:
    s = deepcopy(c)
    shuuki = [1]*n
    for i in range(n):
        score = 0
        prev = i
        for j in range(n):
            if p[prev]-1 == i:
                break
            s[i] += c[p[prev]-1]
            prev = p[prev]-1
            shuuki[i] += 1
    for i in range(n):
        score = 0
        prev = i
        num = k//shuuki[i]
        amari = k%shuuki[i]
        for j in range(amari):
            score += c[p[prev]-1]
            prev = p[prev]-1
        ans = max(ans, s[i]*num+score)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys, copy,itertools
input = sys.stdin.readline

n, k = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

POINT = [[-10**12 for i in range(n)] for j in range(k)]
PLACE = [[0 for i in range(n)] for j in range(k)]
for i in range(n):
  POINT[0][i] = C[P[i]-1]  
  PLACE[0][i] = P[i]-1 #P[i]は1スタートなのでずれる
  #A[0][i] = C[P[i]]
#print(PLACE)
#print(POINT)

tempmax= max(POINT[0])

for j in range(1,k): #日付
  for i in range(n):
    PLACE[j][i]=P[PLACE[j-1][i]]-1
    POINT[j][i]=POINT[j-1][i] + C[PLACE[j][i]]
    tempmax = max(tempmax,POINT[j][i])

#print(PLACE)
#print(POINT)
print(tempmax)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n, k = map(int, input().split())
pp = input().split()
cc = input().split()
npp=np.array(pp, dtype=int)
ncc=np.array(cc, dtype=int)

pointmax=-1E9
nmax=n*10

for istart in range(0,n):
  point=0
  loc=istart
  k_pointmax=-1E9
  k_pointmax2=-1E9
  for ik in range(1,k+1):
    loc=npp[loc]-1
    point+=ncc[loc]
    if (point >= k_pointmax): k_pointmax=point 

    if ((ik % nmax) == 0): 
      if (k_pointmax2 == k_pointmax): 
        break
      else:
        k_pointmax2=k_pointmax
      
  if (k_pointmax >= pointmax): pointmax=k_pointmax

print(pointmax)

Submission status: Time Limit Exceeded

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

s_max = None
for n in range(N):
    s = 0
    p = n + 1
    for k in range(K):
        p = P[p-1]   
        s += C[p-1]

        if not s_max:
            s_max = s
        if s > s_max:
            s_max = s


print(s_max)

Submission status: Time Limit Exceeded

Solution code:
def main():
  n, k = map(int , input().split())
  p_list = list(map(int, input().split()))
  c_list = list(map(int, input().split()))
  dp = [[float('-inf')]*n for _ in range(k+1)]
  dp[0] = [0]*n
  for i in range(k):
    for j in range(n):
      if i==0:
        dp[i+1][p_list[j]-1] = dp[i][j]+c_list[j]
      else:
        dp[i+1][p_list[j]-1] = max(dp[i][p_list[j]-1], dp[i][j]+c_list[j])
  print(max(dp[-1]))

if (__name__=='__main__'):
  main()