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:
import sys
sys.setrecursionlimit(10**5)
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:
import math
x=input()
x0=x.split()
n=int(x0[0])
k=int(x0[1])
p=input()
p=[int(n) for n in p.split()]
c=input()
c=[int(n) for n in c.split()]
if k<n or sum(c)<=0:
    m=-(10**9)
    for i in range(n):
        for l in range(min(k,n)):
            o=i
            s=0
            for j in range(l+1):
                o=p[o]-1
                s+=c[o]
            if m<s:
                m=s
    print(m)
else:
    m=-(10**9)
    x=0
    for i in range(n):
        for l in range(2*n):
            o=i
            s=0
            for j in range(l+1):
                o=p[o]-1
                s+=c[o]
            if m<s:
                m=s
                x=l
    mm=-(10**9)
    for i in range(n):
        for l in range(k-math.floor(k/x)*x):
            o=i
            s=0
            for j in range(l+1):
                o=p[o]-1
                s+=c[o]
            if mm<s:
                mm=s
    print(m*math.floor(k/x)+mm)

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

ans = - 10 ** 10
for i in range(1, n+1):
    base = i
    nxt = p[i]
    cnt = 0
    score = 0
    while True:
        cnt += 1
        if cnt > k:
            break
        score += c[nxt]
        ans = max(ans, score)
        #print("i = ", i, "ans = ", ans, "score = ", score)
        if nxt == base:
            break
        nxt = p[nxt]
    if cnt > k:
        continue
    if k - cnt <= cnt:
        score_tmp = score
        for j in range(k - cnt):
            score_tmp += c[nxt]
            ans = max(ans, score_tmp)
            #print("ans = ", ans, "score_tmp = ", score_tmp, "nxt = ", nxt, "c[nxt] = ", c[nxt])
            nxt = p[nxt]
    else:
        a = (k - cnt) // cnt
        score_tmp = score + score * a
        ans = max(ans, score_tmp)
        for j in range((k - cnt) - a * cnt):
            score_tmp += c[nxt]
            ans = max(ans, score_tmp)
            nxt = p[nxt]


#print("score:", score)

print(ans)

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(3*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=-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: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
L = [0]*N
Max = -10**9
for i in range(N):
    if L[i] != 0:
        continue
    else:
        c = 0
        L[i] = 1
        c += C[i]
        a = P[i] - 1
        Cs = [c]
        Ds = [c]
        l = 1
        while a != i:
            c += C[a]
            Ds.append(C[a])
            a = P[a]-1
            L[a] = 1
            l += 1
            Cs.append(c)
        if c > 0:
            m = -10**9
            k = K % l
            for i in range(1,k+1):
                for j in range(l):
                    if j + i > l:
                        M = Cs[l-1] - Cs[j]+Ds[j] + Cs[i+j-l-1]
                    else:
                        M = Cs[j+i-1]-Cs[j]+Ds[j]
                    if M > m:
                        m = M
            x = K // l
            max0 = c*x+m
        else:
            if K >= l:
                A = [0]*l
                A[0] = Ds[0]
                for i in range(1,l):
                    A[i] = min([A[i-1]+Ds[i],Ds[i]])
                max0 = c - A[l-1]
                if max0 == 0:
                    max0 = max(Ds)
            else:
                m = -10**9
                k = K
                for i in range(1,k+1):
                    for j in range(l):
                        if j + i > l:
                            M = Cs[l-1] - Cs[j]+Ds[j] + Cs[i+j-l-1]
                        else:
                            M = Cs[j+i-1]-Cs[j]+Ds[j]
                        if M > m:
                            m = M
                max0 = m
    if Max < max0:
        Max = max0
print(Max)

Submission status: Wrong Answer

Solution code:
N,K=map(int, input().split())
P=list(map(int, input().split()))
P.insert(0,0)
C=list(map(int, input().split()))
C.insert(0,0)
M=[-10**9 for i in range(N+1)] #空リスト
M[0]=0
for i in range(1,N+1):
    score=0
    now=i#1-N
    for j in range(1,N+1):
        score+=C[P[now]]
        now=P[now]
        M[j]=max(M[j],score)
if K<=N:
    print(max(M[1:K+1]))
else:
    num=K//N
    res=K%N
    if sum(C)>0:
        print(max(sum(C)*num+max(M[0:res+1]),sum(C)*(num-1)+max(M[0:N+1])))
    else:
        print(max(M[1:N+1]))

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
C=[0]+list(map(int,input().split()))
P=[0]+list(map(int,input().split()))
D=[0 for i in range(N+1)]
D[0]=2
ANS=-10**20
for z in range(1,N+1):
    if D[z]==0:
        D[z]=1
        X=[[0,z]]
        for i in range(N*2):
            if D[X[-1][1]]!=3:
                D[X[-1][1]]+=1
                X.append([X[-1][0]+P[C[X[-1][1]]],C[X[-1][1]]])
            else:
                break
        #print(X)
        roop=(len(X)-1)//2
        
        Roop=max(0,X[roop][0])
        #print(roop)
        k=K%roop
        f=0
        if k==0:
            f=1
            k=roop
        cnt=0
        for i in range(1,k+1):
            for j in range(roop):
                #print(i+j,j)
                cnt=max(cnt,X[i+j][0]-X[j][0])
                #print(cnt)
        #print(cnt)
        ANS=max(ANS,(K//roop-f)*(Roop)+cnt)
for i in range(1,N+1):
    if P[i]==i:
        if C[i]*K>ANS:
            ANS=C[i]*K
if max(P[1:])<0:
    print(max(P[1:]))
else:
    print(ANS)

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)-2:
                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:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, k = LI()
p = LI()
c = LI()
C = []
S = []
for i in range(n):
    lst = [-1]*n
    cnt = 0
    idx = i
    s = 0
    while lst[idx] == -1:
        lst[idx] = cnt
        s += c[idx]
        cnt += 1
        idx = p[idx] - 1
    C.append(cnt)
    S.append(s)

if n >= k:
    ans = -10**10
    for i in range(n):
        cnt = 0
        ret = 0
        idx = p[i]
        while cnt < k:
            ret += c[idx-1]
            idx = p[idx-1]
            cnt += 1
            ans = max(ans, ret)
    print(ans)
else:
    ans = -10**10
    for i in range(n):
        if S[i] > 0:
            tmp = S[i] * (k // C[i])
            r = k % C[i]
            cnt = 0
            ret = 0
            idx = p[i]
            ans = max(ans, tmp)
            while cnt < r:
                ret += c[idx-1]
                idx = p[idx-1]
                cnt += 1
                ans = max(ans, tmp + ret)
        else:
            cnt = 0
            ret = 0
            idx = p[i]
            while cnt < n:
                ret += c[idx-1]
                idx = p[idx-1]
                cnt += 1
                ans = max(ans, ret)
    print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
n,k = map(int,input().split())
P = [-1]+list(map(int,input().split()))
C = [-1]+list(map(int,input().split()))
visited = [True]+[False]*n
circles = []
for i in range(1,n+1):
    if not visited[i]:
        pre = i
        visited[i]=True
        s = [C[i]]
        while P[i] != pre:
            s.append(C[P[i]])
            visited[P[i]] = True
            i = P[i]
        circles.append((s,sum(s)))
# print(circles)
ans1 = 0

anslist = []

for ci in circles:
    ci_ans = 0
    if ci[1] > 0:
        ci_ans += ci[1]*k//len(ci[0])
    acc = list(accumulate(ci[0]*2))
    maxi = 0
    ci2 = 2*ci[0]
    for d in range(1,min(len(ci[0]),ci[1]*k % len(ci[0])+1)):
        for i in range(d,len(ci2)):
            maxi = max(maxi,ci2[i]-ci2[i-d])
    ci_ans += maxi
    anslist.append(ci_ans)
print(max(anslist))

Submission status: Wrong Answer

Solution code:
def loop(i, N, K, P, C):
  m = 1
  l = P[i]-1
  score = [C[i]]
  while l != i:
    score.append(C[l] + score[m-1]) 
    m += 1
    l = P[l]-1 
  return score
    
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
ans = 0
for i in range(N):
  score = loop(i, N, K, P, C)
  m = len(score)
  tmp = max(score)
  a = K // m 
  b = K % m
  tmp1 = score[m-1]*a 
  if b != 0:
    tmp2 = max(score[:b])
    if tmp2 > 0:
      tmp1 += tmp2
  tmp3 = max(tmp,tmp1)
  if tmp3 > ans:
    ans = tmp3
print(ans)

Submission status: Wrong Answer

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

from itertools import accumulate

def calc_score(x):
    ans = -10**18
    score = []
    for i in range(1,n+1):
        score = []
        for _ in range(x):
            score.append(c[i])
            i = p[i]
        scores = list(accumulate(score))
        max_score = max(scores)
        if max_score > ans:
            ans = max_score
            
    return ans

if k < n:
    print(calc_score(k))
else:
    ans = calc_score(n)
    if ans <= 0:
        print(ans)
    else:
        q,r = divmod(k, n)
        ans = sum(c) * q + calc_score(r)
        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()))

#到達したかの判定
#masu=[0]*(n+1)
#nは1~n
def junkan(N):
  #到達したかの判定
  masu=[0]*(n+1)
  ans=0
  ans22=-(10**9+1)
  junkan_flag=False
  now_mas=p[N-1]
  count=0
  masu[now_mas]=1
  #このwhileはせいぜい5000
  while True:
    if count!=0 and masu[now_mas]==1:
      junkan_flag=True
      break
    count+=1
    ans+=c[now_mas-1]
    
    if ans22<=ans:
      ans22=ans
      
    masu[now_mas]=1
    now_mas=p[now_mas-1]
  if junkan_flag==True and ans>0:
    ans=(k//count)*ans
    
    if ans22<=ans:
      ans22=ans
      
    for i in range(k-(k//count)*count):
      ans+=c[now_mas-1]
      
      if ans22<=ans:
        ans22=ans
        
      now_mas=p[now_mas-1]
    return max(ans,ans22)
  
  else:
    return max(ans,ans22)
answ=-(10**9+1)

for i in range(1,n+1):
  hantei=junkan(i)
  if answ <= hantei:
    answ=hantei
print(answ)

Submission status: Wrong Answer

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

INF=10**10

vis=[0]*(N+1)

def find_cycle(start):
  vis[start]=1
  his=[start]
  now=start
  cost=[]
  while 1:
    new = P[now-1]
    cost.append(C[new-1])
    if vis[new]==1:
      return cost
    his.append(new)
    vis[new]=1
    now=new

costs=[]
for i in range(N):
  if not vis[i+1]:
    cost=find_cycle(i+1)
    costs.append(cost)
    
def cumsum(array):
    new=[0]
    for i in range(len(array)):
        new.append(array[i]+new[-1])
    return new 
    
cumcost=[]
for i in range(len(costs)):
  cost=costs[i]
  cumcost.append(cumsum(cost*2))
  
def best_margin_cost(idx,r1):
  out=-INF
  for r2 in range(1,r1+1):
    for i in range(len(costs[idx])):
      tmp = cumcost[idx][i+r2]-cumcost[idx][i]
      out = max(tmp,out)
  return out
  
def opt_cost(idx):
  l = len(costs[idx])
  SUM = sum(costs[idx])
  q,r=divmod(K,l)
  if K>=l:
    return max(SUM,0)*q+best_margin_cost(idx,l)
  else:
    return best_margin_cost(idx,K)

ans = -INF
for i in range(len(costs)):
  ans = max(ans,opt_cost(i))
  
print(ans)

Submission status: Wrong Answer

Solution code:
#ceilevenoddformula
import math
from queue import PriorityQueue
import bisect
import copy
import time
from collections import Counter
#map(int,input().split())
#int(x) for x in input().split()
def su(x,k):
	ans=[]
	for i in range(min(k,len(x))):
		d=sum(x[:i+1])
		m=d
		for j in range(i+1,min(k,len(x))):
			d=d-x[j-i-1]+x[j]
			if m<d:
				m=d
		ans.append(m)
	return ans


n,k=map(int,input().split())
p=[int(x) for x in input().split()]
c=[int(x) for x in input().split()]
l=[]
v=set()
for i in range(n):
	if i not in v:
		f=[]
		f.append(c[i])
		v.add(i)
		x=p[i]
		while x not in v:
			f.append(c[x-1])
			v.add(x-1)
			x=p[x-1]
		l.append(f)
value=float('-INF')
for i in range(len(l)):
	ans=su(l[i],k)
	if len(ans)>0:
		jk=0
		if k<=len(l[i]) or sum(l[i])<=0:
			jk+=max(ans)
		else:
			if sum(l[i])>0:
				jk+=(k//len(l[i]))*sum(l[i])
				b=k%len(l[i])
				if b>0:
					jk+=max(ans[:b])
		value=max(value,jk)

print(value)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
@author: H_Hoshigi
"""
def main():
    N, K = map(int, input().split())
    P_lsit = list(map(int, input().split()))
    C_lsit = list(map(int, input().split()))

    max_score = max(C_lsit)
    for start in range(N):
        #print(f"start={start}")
        visited_set = set()
        #visited_set.add(start)
        score_list = []
        now_position = start
        next_position = P_lsit[now_position]-1
        while next_position not in visited_set:
            #print(f"next_position={next_position}")
            if visited_set or now_position != start:
                visited_set.add(now_position)
            if score_list:
                score_list.append(score_list[-1]+C_lsit[next_position])
            else:
                score_list.append(C_lsit[next_position])
            now_position = next_position
            next_position = P_lsit[now_position]-1
            #print(f"now_position={now_position}, next_position={next_position}")
        #print(score_list)
        score_list = score_list[-1:] + score_list[:-1]
        if K <= len(visited_set):
            max_score = max(max_score, max(score_list))
        else:
            if score_list[-1] > 0:
                new_score_list = \
                    [ s + score_list[-1]*(K//len(score_list)) for s in score_list[:K%len(score_list)]] + \
                    [ s + score_list[-1]*(K//len(score_list) - 1) for s in score_list[K%len(score_list):]]
                max_score = max(max_score, max(new_score_list))
                #print(new_score_list)
    print(max_score)


if __name__ == "__main__":
    main()

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[:k]), ans)
        
else:
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), ans)
        
print(ans)

Submission status: Wrong Answer

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  N,K=LI()
  P=LI()
  P=[0]+P
  C=LI()
  C=[0]+C

  l=[[0] for _ in range(N)]
  check=[[False]*(N+1) for _ in range(N)]
  roop=[]
  for i in range(N):
    zahyo=i+1
    check[i][zahyo]=True
    f=False
    for j in range(N+1):
      zahyo=P[zahyo]
      if check[i][zahyo] and not f:
        roop.append(j+1)
        f=True
      score=C[zahyo]
      l[i].append(l[i][-1]+score)
  # print(l)
  # print(roop)

  ans=-inf
  for i in range(N):
    roop_count=roop[i]
    if K<=roop_count:
      ans=max(ans,max(l[i][1:K+1]))
    else:
      ans=max(ans,max(l[i][1:K+1]))
      if l[i][roop_count]>0:
        c=K//roop_count
        _ans1=c*l[i][roop_count]
        k=K%roop_count
        _ans1+=max(l[i][1:k+1]+[0])
        ans=max(ans,_ans1)
        # if c>=1:
        #   _ans2=(c-1)*l[i][roop_count]
        #   _ans2+=max(l[i][1:K+1])
        #   ans=max(ans,_ans1,_ans2)

  return ans

# main()
print(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()))

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

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
loop_flags = [False] * N
loops = []
for i in range(N):
    if loop_flags[i]:
        continue
    next_cell = i
    loop = []
    while not loop_flags[next_cell]:
        loop_flags[next_cell] = True
        loop.append(C[next_cell])
        next_cell = P[next_cell] - 1
    if loop:
        loops.append(loop)
# print(loops)

ans = -float('inf')
for loop in loops:
    sum_score = 0
    for l in loop:
        sum_score += l
    if sum_score > 0:
        sum_val = sum_score * (K // len(loop))
        remain_K = K % len(loop)
    else:
        sum_val = 0
        remain_K = min(len(loop), K)
    for i in range(1, len(loop)):
        target = sum_val
        for j in range(i):
            target += loop[j]
        ans = max(target, ans)
        for j in range(len(loop)):
            target = target - loop[j] + loop[(i + j) % len(loop)]
            ans = max(target, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")

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

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

ans=0
check=set()

for i in range(N):
    
    if i in check:
        continue
    
    # create loop
    tmpK=K
    tmpans=0
    loop_check=set()
    tmp_idx=i
    loop=[]
    while tmp_idx not in loop_check:
        loop.append(C[tmp_idx])
        loop_check.add(tmp_idx)
        check.add(tmp_idx)
        tmp_idx=P[tmp_idx]
    
    S=sum(loop)
    L=len(loop)
    if S>=0:
        tmpans=S*(tmpK//L)
        tmpK%=L
    
    # 部分最大列を検索
    #print('loop',loop)
    loop*=2
    for i in range(len(loop)-1):
        loop[i+1]+=loop[i]
    n=2*L
    def init_min(init_min_val):
        #set_val
        for i in range(n):
            seg_min[i+num_min-1]=init_min_val[i]    
        #built
        for i in range(num_min-2,-1,-1) :
            seg_min[i]=min(seg_min[2*i+1],seg_min[2*i+2])
    def query_min(p,q):
        if q<=p:
            return ide_ele_min
        p += num_min-1
        q += num_min-2
        res=ide_ele_min
        while q-p>1:
            if p&1 == 0:
                res = min(res,seg_min[p])
            if q&1 == 1:
                res = min(res,seg_min[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = min(res,seg_min[p])
        else:
            res = min(min(res,seg_min[p]),seg_min[q])
        return res
    #####単位元######
    ide_ele_min = 10**15
    #num_min:n以上の最小の2のべき乗
    num_min =2**(n-1).bit_length()
    seg_min=[ide_ele_min]*2*num_min

    init_min(loop)
    local_max=0
    for i,v in enumerate(loop):
        if i>=L:
            #print('v,min=',v,query_min(max(0,i-tmpK),i),v-query_min( max(0,i-tmpK),i ))
            local_max=max(local_max,v-query_min( max(0,i-tmpK),i ) )

    local_max2=0
    for i,v in enumerate(loop):
        if i>=L:
            #print('v,min=',v,query_min(max(0,i-tmpK),i),v-query_min( max(0,i-tmpK),i ))
            local_max2=max(local_max2,v-query_min( max(0,i-K),i ) )
    
    ans=max(ans,local_max+tmpans,local_max2)

if ans==0:
    print(max(C))
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
def main():
    n, k = map(int, input().split())
    P = list(map(int, input().split()))
    C = list(map(int, input().split()))
    m = max(C)
    if m <= 0:
        print(m)
        exit()
    i, c = 0, 0
    G = []
    g = []
    v = [False] * n
    while c < n:
        if v[i]:
            G.append(g)
            g = []
            i = v.index(False)
        g.append(i)
        v[i] = True
        i = P[i] - 1
        c += 1
    if g != []:
        G.append(g)
    ans = 0
    for g in G:
        score = [C[gg] for gg in g]
        S = [0] + list(accumulate(score * 2))
        ln = len(score)
        p = k % ln
        c = max(0, sum(score)) * (k // ln)
        l, r = 0, 1
        while l < ln:
            if r - l > p:
                l += 1
                r = l + 1
            ans = max(ans, S[r] - S[l] + c)
            r += 1



    print(ans)






if __name__ == '__main__':
    main()