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: Wrong Answer

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)
    
for i,value in enumerate(D2):
    ans3=value*(K//L[i])
    for j in D1[i]:
        ans=0
        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: Wrong Answer

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

    d = [c[p[i]-1] for i in range(n)]
    e = [0]
    for i in range(1,n+1):
        e.append(e[i-1] + d[i-1])
    
    if(max(d) <= 0):
        print(max(d))
        return

    s = e[n]
    temp = 0
    for i in range(n+1):
        for j in range(i+1,n+1):
            if(n - (j-i) < k):
                temp = max(temp,s - (e[j] - e[i]),0)
    
    for i in range(n+1):
        for j in range(i+1,n+1):
            if(j-i < k):
                temp = max(temp,e[j]-e[i],0)


    if(s > 0):
        temp += s * (k//n)
    print(temp)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def resolve():
  n,k=map(int,input().split())
  p=list(map(int,input().split()))
  c=list(map(int,input().split()))
  visit=[False]*n
  group_l=[[] for _ in range(n)]
  group_n=0
  for i in range(n):
    if visit[i]==True:
      continue
    group_l[group_n].append(c[i])
    visit[i]=True
    bp=p[i]-1
    while visit[bp]==False:
      group_l[group_n].append(c[bp])
      visit[bp]=True
      bp=p[bp]-1
    group_n+=1
  ans=-10**9+1
  for g in range(group_n):
    len_g=len(group_l[g])
    a=k//len_g
    b=k%len_g
    sum_g=sum(group_l[g])
    group_l[g]+=group_l[g]+group_l[g]
    if a==0:
      m=b
    elif sum_g<0:
      m=len_g
    else:
      m=len_g+b
    x=-10**9-1
    for mi in range(1,m+1):
      csum=sum(group_l[g][:mi])
      msum=csum
      for i in range(1,len_g):
        csum+=group_l[g][i+mi-1]-group_l[g][i-1]
        msum=max(msum,csum)
      x=max(x,msum)
    if sum_g>0 and a>0:
      x=sum_g*(a-1)+x
    ans=max(ans,x)
  print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline
INF = 10**18

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

    ans = -INF
    for start in range(N):
        T = K
        S = {start: 0}
        seq = {start: 0}
        t = start
        while T > 0 and not P[t]-1 in S:
            seq[P[t]-1] = seq[t] + 1
            S[P[t]-1] = S[t] + C[P[t]-1]
            ans = max(ans, S[P[t]-1])
            t = P[t] - 1
            T -= 1
        if T > 0:
            scoredelta = S[t] + C[P[t]-1] - S[P[t]-1]
            cycle = seq[t] + 1 - seq[P[t] - 1]
            score = S[P[t]-1]
            T += cycle - 1
            count = T // cycle
            T -= count * cycle
            score += count * scoredelta
            ans = max(ans, score)
            t = P[t]-1
            while T > 0:
                score += C[t]
                ans = max(ans, score)
                t = P[t]-1
                T -= 1
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
g = [[0]*(n) for _ in range(n)]
A = [n]*n
for i in range(n):
    tmp = 0
    idx = i
    cnt = 0
    set_ =set()
    while cnt<n:
        if C[idx] not in set_:
            tmp += C[idx]
            set_.add(C[idx])
            g[i][cnt] = tmp
            idx = P[idx]-1
            cnt += 1
        else:
            p = len(set_)
            A[i] = p
            break
ans = -float('inf')

for i in range(n):
    v,w = k//A[i],k%A[i]
    if A[i]<k:
        if g[i][A[i]-1]>0:
            val1 = v*g[i][A[i]-1]
        elif g[i][A[i]-1]==0:
            val1 = 0
        else:
            val1 = -float('inf')
        val2 = -float('inf')
        for j in range(w):
            val2 = max(val2,g[i][j])
        ans = max(ans,val1+val2,val1,val2)
    else:
        for j in range(k):
            ans = max(ans,g[i][j])
print(ans)

Submission status: Wrong Answer

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

done = [0]*n

def cycle(st):
    global done
    visited = [0]*n
    visited[st] = 1
    idx = P[st]
    cyc = 0
    sco = [0]
    for _ in range(n):
        done[idx] += 1
        visited[idx] += 1
        cyc += 1
        sco.append(sco[-1] + C[idx])
        if visited[idx] > 1: break
        else: idx = P[idx]
    return cyc, sco

ans = -10**18

for i in range(n):
    #if done[i] > 0: continue

    cyc, sco = cycle(i)

    if sco[-1] > 0:
        # 繰り返したほうが得
        d, m = divmod(k, cyc)
        v = d * sco[-1] + max(sco[:m+1])
        #v = d * sco[-1] + (max(sco) - min(sco))
    else:
        # 早期打ち切り
        v = max(sco[1:k+1])
        #v = max(sco[1:])
        #v = max(sco) - min(sco)

    ans = max(ans, v)
    #print(i, cyc, sco, v)

print(ans)

Submission status: Wrong Answer

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

visit = {i: False for i in range(N)}
Clistlist = []
for i in range(N):
    if not visit[i]:
        visit[i] = True
        Clist = [C[i]]
        curi = P[i]

        while not visit[curi - 1]:
            Clist.append(C[curi - 1])
            visit[curi - 1] = True
            curi = P[curi - 1]
            # Clist.append(C[curi - 1])
        Clistlist.append(Clist)

largest = -1 * (10 ** 9)
# print(Clistlist)

for Clist in Clistlist:
    clen = len(Clist)
    Kd = K % clen
    sum_max = -1 * (10 ** 9)
    # 1loopが負のとき
    if sum(Clist) <= 0:
        for i in range(clen):
            ssum = 0
            for j in range(min(K, clen)):
                ssum += Clist[(i + j) % clen]
                sum_max = max(sum_max, ssum)
    # 1loopが正のとき
    else:
        for i in range(clen):
            # print(Kd, clen)
            ssum = 0
            for j in range(min(Kd, clen)):
                ssum += Clist[(i + j) % clen]
                sum_max = max(sum_max, ssum)
                # print(ssum)
            if min(Kd, clen) == 0:
                sum_max = 0
        sum_max += int(K / clen) * sum(Clist)
    # print(sum_max)
    largest = max(largest, sum_max)
print(largest)

Submission status: Wrong Answer

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

ps = [p-1 for p in ps]

visited = []
coarses = []
scores = []
while True:
    if len(visited) == n:
        break

    now = list(set(ps) - set(visited))[0]
    coarse = []
    score = []
    s, pre_s = 0, 0

    while True:
        nxt = ps[now]
        if nxt in visited:
            break

        s += cs[now]
        if cs[now] > 0:
            score.append(dict(bgn=pre_s, now=s, max=s))

        for sc in score:
            sc["now"] = s
            if sc["now"] > sc["max"]:
                sc["max"] = sc["now"]

        visited.append(nxt)
        coarse.append(nxt)
        now = nxt
        pre_s = s
    
    scores += score
    coarses.append(coarse)

s_cands = []
for score in scores:
    s_cands.append(score["max"] - score["bgn"])

for coarse in coarses:
    sm = 0
    for i in coarse:
        sm += cs[i]
    s_cands.append(sm * (k // len(coarse)))

print(max(s_cands))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
mx=-float("inf")


for i in range(n):

  sc=0
  pn=i
  mass=[0]*n
  for j in range(k):
    if mass[pn]!=0:
      lpk=j-mass[pn][0]
      amari=(k-j)%lpk
      lpsc=sc-mass[pn][1]
      if lpsc<=0:
        mx=max(mx,sc)
        break
      for l in range(amari):
        pn=p[pn]-1
        sc+=c[pn]
        mx=max(mx,sc)
      sc+=lpsc*((k-j-amari)//lpk)
      mx=max(mx,sc)
      break
    mass[pn]=[j,sc]
    pn=p[pn]-1
    sc+=c[pn]
    mx=max(mx,sc)
print(mx)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
c = [1] * N
s = [C[P[i]-1] for i in range(N)]
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
    m[i][1] = (C[P[i]-1])
for i in range(N):
    j = i
    while P[j]-1 != i:
        j = P[j]-1
        c[i] += 1
        s[i] += C[P[j]-1]
        if  c[i] <= K:
            if s[i] > m[i][c[i]-1]:
                m[i][c[i]] = s[i]
            else:
                m[i][c[i]] = m[i][c[i]-1]
ans = max(C)
for i in range(N):
    if s[i] > 0:
        if  s[i] * (K//c[i]) + m[i][K%c[i]] > ans:
            ans = s[i] * (K//c[i]) + m[i][K%c[i]]
    else:
        if max(m[i][1:min(c[i],K+1)]) > ans:
            ans = max(m[i][1:min(c[i],K+1)])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

def main():
	#a = int(input())
	n, k = tin()
	#s = input()
	al = lin()
	cl=lin()
	dd=[0]*n
	for i in range(n):
		if dd[i]!=0:
			continue
		cc=set()
		pos = i
		point=0
		n_node=0
		while pos not in cc:
			cc.add(pos)
			pos=al[pos]-1
			point+=cl[pos]
			n_node+=1
			
		for p in cc:
			dd[p] = (point, n_node)
	
	ret=-mod*mod
	for i in range(n):
		pi, ni = dd[i]
		if pi < 0:
			point=0
			pmax=-mod*mod
			pos=i
			for _ in range(ni):
				cc.add(pos)
				pos=al[pos]-1
				point+=cl[pos]
				pmax = max(pmax, point)
			ret = max(ret, pmax)
		else:
			point = pi*(k//ni)
			nk=k%ni
			pos = i
			for _ in range(nk):
				cc.add(pos)
				pos=al[pos]-1
				point+=cl[pos]
			ret = max(ret, point)
	return ret
		
		
			
	
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 63


def run():
    N, K = map(int, sysread().split())
    P = list(map(int, sysread().split()))
    C = list(map(int, sysread().split()))
    P = [p-1 for p in P]

    loops = []
    checked = [0] * N
    loop = [0]
    for i in range(N):
        current = i
        while True:
            if not checked[current]:
                checked[current] = 1
                loop.append(C[current])
                current = P[current]
            else:
                if len(loop) == 1:break
                loops.append(loop)
                loop = [0]
                break
    loopSums = []
    for loop in loops:
        val = 0
        tmp = []
        for l in loop:
            val += l
            tmp.append(val)
        loopSums.append(tmp)
    #print(loops)
    #print(loopSums)
    ans = -INF
    for loop, loopSum in zip(loops, loopSums):
        for i in range(1, len(loop)):
            val = 0
            if loopSum[-1] <= 0 or K <= len(loop)-1:
                j = i
                max_val = -INF
                iter = 0
                done = False
                while iter <= K:
                    if j >= len(loop):j=0
                    if (i != j and j) or done:
                        val += loop[j]
                        max_val = max(val, max_val)
                    j += 1
                    iter += 1
                    if done : break
                    if i == j: done = True
                ans = max(ans, max_val)
                continue


            rest = K
            #if K <= len(loop) - i - 1:
            #    val += loopSum[i + K - 1] - loopSum[i]
            #    ans = max(ans, val)
            #    continue
            rest -= len(loop) - i - 1
            val += loopSum[-1] - loopSum[i]
            val += (rest // (len(loop)-1)) * loopSum[-1]
            rest = rest % (len(loop) - 1)
            val += max(loopSum[0:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

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

c = list(map(int, input().split(' ')[:n]))
for i in range(n):
	fin=p[i]
	score=c[fin]
	ans=max(ans,score)
	cnt=1
	while fin!=i and cnt<k:
		fin=p[fin]
		score+=c[fin]
		ans=max(ans,score)
		cnt+=1
	if k>cnt:
		temp=k//cnt
		if score>0:
			score=temp*score
			ans=max(ans,score)
			r=k%cnt
			sam = 0
			while sam!=r:
				fin=p[fin]
				score+=c[fin]
				ans=max(ans,score)
				sam+=1
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

def calc_counts(K, Clist):
    lenC, sumC = len(Clist), sum(Clist)
    counts = -1e10
    fracK = K % lenC if K!=lenC else K
    Clist = np.concatenate((Clist, Clist))
    for i in range(lenC):
        for j in range(1, fracK+1):
            sum_c = sum(Clist[i:i+j])
            if sum_c > counts:
                counts = sum_c

    if K > lenC and sumC > 0:
        counts += K//lenC * sumC
    return counts

def check():
    N, K = list(map(int, input().split(' ')))
    Plist = list(map(int, input().split(' ')))
    Clist = np.asarray(list(map(int, input().split(' '))))

    use_list, loop_table = list(), list()
    use_append, loop_append = use_list.append, loop_table.append
    for i in range(N):
        pn = Plist[i]
        if pn not in use_list:
            loop = list()
            while True:
                loop.append(pn-1)
                use_append(pn)
                pn = Plist[pn-1]
                if pn in use_list:
                    break
            loop_append(loop)
    
    max_counts = -1e10
    for loop in loop_table:
        counts = calc_counts(K, Clist[loop])
        if counts > max_counts:
            max_counts = counts
    return max_counts
    
print( check() )

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
N, K = map(int, input().split())
P = list(map(lambda x:int(x)-1, input().split()))
C = list(map(int, input().split()))
weight = []
visited = [0]*N
ans = - float('inf')

def dfs(u, cnt, w):
  w += [C[u]]
  visited[u] = 1
  v = P[u]
  if visited[v] != 1:
    dfs(v, cnt+1, w)
  else:
    return

for i in range(N):
  weight = []
  visited = [0]*N
  dfs(i, 1, weight)
  if len(weight) > K:
    tmp = 0
    for j in range(len(weight)):
      if weight[j] > 0:
        tmp += weight[j]
      if tmp == 0:
        tmp = weight[0]
    ans = max(ans, tmp)
  else:
    s = sum(weight)
    if s > 0:
      ans = max(ans, (K//len(weight))*s + sum(weight[:K%len(weight)]))
    else:
      tmp = 0
      for j in range(min(K, len(weight))):
        if weight[j] > 0:
          tmp += weight[j]
      if tmp == 0:
        tmp = weight[0]
      ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

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

L = [[] for i in range(n+1)]
length = [0]*(n+1)

for i in range(1,n+1):
    x = i

    s = set([])
    sw = 0
    for j in range(1,n+1):

        x = P[x]
        if P[x] in s and sw == 0:
            length[i] = j-1
            sw = 1
            
        s.add(P[x])
        point = C[x]
        if L[i] != []:
            L[i].append(L[i][-1]+C[x])
        else:
            L[i].append(C[x])
            
    if sw == 0:
        length[i] = n


ans = - float("Inf")

if k > n:

    for i in range(1,n+1):
        m = k//length[i]
        p = k%length[i]
        if p == 0:
             point = m * L[i][length[i]-1]
        else:
            point = m * L[i][length[i]-1] + max(L[i][:p])

        ans = max(ans, point)
    
    for a in L[1:]:
        if a != []:
            ans = max(max(a), ans)
        
else:
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), ans)
        
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right
from itertools import accumulate

sys.setrecursionlimit(10**6)
INF = 10**18
m = 10**9 + 7

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

    ans = - INF
    used = [0] * N
    candidate = []

    for i in range(N):
        if used[i]: continue
        now = i
        used[i] = 1
        tmp = [i]
        
        while P[now]-1 not in tmp:
            used[P[now]-1] = 1
            tmp.append(P[now]-1)
            now = P[now]-1
        
        candidate.append(tmp)

    # 各ループごとにK回以内で回して最大値を調べていく
    for tmp in candidate:
        M = len(tmp)
        accumT = []
        for t in tmp:
            accumT.append(C[t])
        accumT = [0] + list(accumulate(accumT*2))

        if K <= M:# ループにならない
            res = - INF
            for i in range(2*M+1):
                for j in range(i+1,2*M+1):
                    if j - i > K: 
                        break
                    res = max(res,accumT[j]-accumT[i])
            ans = max(ans,res)
        else:
            SUM = accumT[M]
            if SUM > 0:
                addition = SUM * (K//M)
                res = - INF
                for i in range(2*M+1):
                    for j in range(i+1,2*M+1):
                        if j - i > K%M: 
                            break
                        res = max(res,accumT[j]-accumT[i])
                ans = max(ans,res+addition)
            else:
                # M回までやる
                res = - INF
                for i in range(2*M+1):
                    for j in range(i+1,2*M+1):
                        if j - i > M:
                            break
                        res = max(res,accumT[j]-accumT[i])
                ans = max(ans,res)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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


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


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

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

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


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

    ret = 0
    for i, loop in enumerate(loops):
        if loopScore[i] > 0:
            baseScore = loopScore[i] * (K // len(loop))
            r = K % len(loop)
            maxscore = 0
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                    maxscore = max(maxscore, max(scores))
            ret = max(maxscore + baseScore, ret)
        else:
            r = len(loop)
            maxscore = 0
            for i in range(r):
                for x in loop:
                    scores[x] += CS[pos[x]]
                    pos[x] = PS[pos[x]]
                    maxscore = max(maxscore, max(scores))
            ret = max(maxscore, ret)

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


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


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

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

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

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


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


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


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

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

main()

Submission status: Wrong Answer

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
            break
        else:
            visited[now] = True

print(max(ans))

Submission status: Wrong Answer

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

max_score = -1000000000
for i in range(n):
    score = 0
    count = 0
    start = p[i]-1
    now = start
    for _ in range(k):
        score += c[now]
        max_score = max(max_score,score)
        now = p[now]-1
        count += 1
        if now == start:
            if score < 0:
                break
            else:
                m = k // count
                max_score = score * m
                break
print(max_score)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
c = [1] * N
s = [C[P[i]-1] for i in range(N)]
m = [[0] * (N+1) for i in range(N)]
for i in range(N):
    m[i][1] = (C[P[i]-1])
for i in range(N):
    j = i
    while P[j]-1 != i:
        j = P[j]-1
        c[i] += 1
        s[i] += C[P[j]-1]
        if  c[i] <= K:
            if s[i] > m[i][c[i]-1]:
                m[i][c[i]] = s[i]
            else:
                m[i][c[i]] = m[i][c[i]-1]
ans = min(C)
for i in range(N):
    if s[i] > 0:
        if  s[i] * (K//c[i]) + m[i][K%c[i]] > ans:
            ans = s[i] * (K//c[i]) + m[i][K%c[i]+1]
    else:
        if max(m[i][1:min(c[i],K+1)]) > ans:
            ans = max(m[i][1:min(c[i],K+1)])
print(ans)

Submission status: Wrong Answer

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
INF = 10**10
def main(N, K, P, C):
    ans = max(C)
    for i in range(N):
        used = [False] * N
        now = 0
        mx = -INF
        cnt = 0
        while True:
            if used[i]:
                break
            used[i] = True
            i = P[i] - 1
            now += C[i]
            mx = max(mx, now)
            cnt += 1
        tmp = max(mx, now)
        if now > 0:
            cycle, mod = divmod(K, cnt)
            if cycle > 1:
                tmp = max(tmp, now * (cycle - 1) + mx)
            t = now * cycle
            tmp = max(tmp, t)
            for j in range(mod):
                i = P[i] - 1
                t += C[i]
                tmp = max(tmp, t)
        ans = max(ans, tmp)
    print(ans)

if __name__ == '__main__':
    input = sys.stdin.readline
    N, K = map(int, input().split())
    *P, = map(int, input().split())
    *C, = map(int, input().split())
    main(N, K, P, C)

Submission status: Wrong Answer

Solution code:
(n, k), p, c = [[*map(int, i.split())] for i in open(0)]
visit = [0] * n
visit[0] = 1
loop = [0] * n
count = a = 0
while True:
    a = p[a] - 1
    if visit[a]:
        if loop[a]:
            break
        count += c[a]
        loop[a] = 1
    visit[a] = 1

ln = sum(loop)


def solve(x, t):
    ans = c[p[x] - 1]
    l = True
    sub = 0
    while True:
        if loop[x] and l:
            if count > 0 and t > ln:
                sub += (t // ln - 1) * count
                t -= (t//ln-1)*ln
            else:
                t %= ln+1
            l = False
        if t < 1:
            ans = max(sub, ans)
            return ans
        x = p[x] - 1
        sub += c[x]
        t -= 1
        ans = max(sub, ans)


print(max(solve(i, k) for i in range(n)))