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
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 = 2,2
#P = [1,2]
#C = [10,9]
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]
    cumsum = [0]
    for v in vals2:
        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)
        for left in range(0,2*l-r):
            for right in range(left+1,left+r+1):
                gh.append(cumsum[right] - cumsum[left])
        if gh:
            temp = max(gh)
        if s > 0:
            temp += q * s
    #print(temp)
    cand.append(temp)
if cand:
    print(max(cand))

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

flag = [False for i in range(n + 1)]
r = []
num = 1
while num < n + 1:
    if flag[num] == False:
        temp = [c[num]]
        flag[num] = True
        num2 = p[num]
        while flag[num2] == False:
            flag[num2] = True
            temp.append(c[num2])
            num2 = p[num2]
        else:
            r.append(temp)
            num += 1
    else:
        num += 1
ans = -float("inf")
for i in r:
    temp = sum(i)
    sum_i = [0]
    for j in range(len(i)):
        sum_i.append(sum_i[-1] + i[j])
    for j in range(len(i)):
        sum_i.append(sum_i[j + 1] + temp)
    num1 = k % len(i)
    num2 = k // len(i)
    if temp < 0:
        for j in range(1, min(len(i), k) + 1):
            for l in range(len(i)):
                ans = max(ans, sum_i[l + j] - sum_i[l])
    else:
        if num2 >= 1:
            for j in range(1, len(i) + 1):
                for l in range(len(i)):
                    ans = max(ans, sum_i[l + j] - sum_i[l] + temp * (num2 - 1))
            for j in range(1, num1 + 1):
                for l in range(len(i)):
                    ans = max(ans, sum_i[l + j] - sum_i[l] + temp * num2)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(x) for x in input().split()]
temp = [int(x) for x in input().split()]
p = [-1]
for x in temp:
    p.append(x)
c = [-1]
temp = [int(x) for x in input().split()]
for x in temp:
    c.append(x)

ans = -int(1e12)
# print(p)
# print(c)
# print()
for i in range(1, N+1):
    # print("i: ", i)
    visited = [False] * (N+1)
    cur_sum = 0
    cur_box = i
    l = 0
    k = K
    while k > 0:
        if visited[cur_box]:
            break
        cur_sum += c[p[cur_box]]
        ans = max(ans, cur_sum)
        visited[cur_box] = True
        cur_box = p[cur_box]
        k -= 1
        l += 1
        # print(cur_sum)
    if(k != 0):
        cur_sum = (cur_sum * (K // l))
        ans = max(ans, cur_sum)
        k = K % l
        while k > 0:
            cur_sum += c[p[cur_box]]
            ans = max(ans, cur_sum)
            cur_box = p[cur_box]
            k -= 1
            # print(cur_sum)
    
    # print("i:", i , ", sum:", cur_sum)
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()))
for i in range(N):
    P[i] -= 1

ans = -10**10
for i in range(N):
    T = []
    Check = [0]*N
    move = i
    count = 1
    while(True):
        if Check[move] != 0:
            break
        Check[move] = count
        T.append(C[P[move]])
        move = P[move]
        count += 1
    s = Check[move] - 1
    result_1 = -10**10
    total = 0
    for j in range(min(s, K)):
        total += T[j]
        result_1 = max(result_1, total)
    result_2 = -10**10
    total = 0
    for j in range(min(len(T), K)):
        total += T[j]
        result_2 = max(result_2, total)
    if K >= len(T):
        result_3 = 0
        result_3 += sum(T[:s])
        result_3 += sum(T[s:])*((K - len(T[:s])) // len(T[s:]))
        result_4 = result_3
        total = result_3
        for j in range((K - len(T[:s])) % len(T[s:])):
            total += T[j]
            result_3 = max(result_3, total)
        total = result_4
        for j in T[:s][::-1]:
            total -= j
            result_4 = max(result_4, total)
    if K >= len(T):
        ans = max([result_1, result_2, result_3, result_4, ans])
    else:
        ans = max([result_1, result_2, ans])
print(ans)

Submission status: Wrong Answer

Solution code:
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

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

dic_s={}
dic_i={}

for i in range(1,n+1):
    if not i in dic_i:
        dic_s[i]=0
        j=i
        while not j in dic_i:
            dic_i[j]=1
            j=p[j-1]
            dic_s[i]+=1

ans=-float('inf')
for i in dic_s.keys():
    lst_c=[]
    # print(i)
    for j in range(dic_s[i]):
        i=p[i-1]
        lst_c.append(c[i-1])
    # print(lst_p)
    # print(lst_c)
    # print(i)
    cnt=0
    sm=sum(lst_c)
    if sm>0 and k>=dic_s[i]:
        cnt+=sm*(k//dic_s[i])
        lst=lst_c+lst_c
        cnt2=-float('inf')
        for j in range(dic_s[i]):
            tmp=0
            for l in range(k%dic_s[i]):
                tmp+=lst[j+l]
                cnt2=max(cnt2,tmp)
            # print(cnt2)
        ans=max(ans,cnt+cnt2)
    else:
        lst=lst_c+lst_c
        cnt2=-float('inf')
        for j in range(dic_s[i]):
            tmp=0
            for l in range(min(k,dic_s[i])):
                tmp+=lst[j+l]
                cnt2=max(cnt2,tmp)
            # print(cnt2)
        ans=max(ans,cnt2)

print(ans)

Submission status: Wrong Answer

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

minusOnly = True
for i in range(n):
    if c[i] > 0:
        minusOnly = False
        break

if minusOnly:
    print(max(c))
    exit()

ans = 0
used = [False]*n

for st in range(n):
    if not used[st]:
        gr = []
        now = st
        gr.append(st)
        used[st] = True
        while True:
            now = p[now]
            gr.append(now)
            used[now] = True
            if now == st:
                break
        gr.pop()

        cs = [c[i] for i in gr]
        cs.sort(reverse = True)
        s = sum(cs)
        point = 0
        r = k
        if k > len(gr) and s > 0:
            point += s*(k//len(gr))
            r -= len(gr)*(k//len(gr))
        
        for i in range(r):
            if cs[i] > 0:
                point += cs[i]
            else:
                break
        ans = max(ans, point)

print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().rstrip().split(" "))
P = list(map(int,input().rstrip().split(" ")))
C = list(map(int,input().rstrip().split(" ")))
ans = -(10 ** 15)
for i in range(N):
    kans = 0
    score = [0]
    nex = P[i] -1
    while True:
        score.append(score[-1] + C[nex])
        nex = P[nex] - 1
        if nex == P[i] -1:
            break;

    if score[-1] > 0:
        if score[1:(K % (len(score) -1)) + 1] != []:
            kans = score[-1] * (K // (len(score) -1)) + max(score[1:(K % (len(score) -1)) + 1])
        else:
            kans = score[-1] * (K // (len(score) -1))
    else:
        if score[1:min(len(score) - 1,K) + 1] != []:
            kans = max(score[1:min(len(score) - 1,K) + 1])
        else:
            kans = -(10 ** 15)
    ans = max(ans,kans)
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()))
ans = -10000000000
for i in range(N):
    check = {i}
    loop_score =[]
    k = i
    while True:
        loop_score.append(C[k])
        k = P[k]-1
        t = len(check)
        check.add(k)
        if len(check)==t:
            break
    cum_score = 0
    cum_scores = []
    for j in loop_score:
        cum_score+=j
        cum_scores.append(cum_score)
    loop = cum_scores[-1]
    compare = -10000000000
    loops = K//len(cum_scores)
    plus = K%len(cum_scores)
    if loop > 0:
        compare = 0
        compare+=loops*loop
    final = cum_scores[:plus]
    v = min(len(cum_scores),K)
    second = cum_scores[:v]
    if plus != 0:
        compare+=max(final)
    if max(second)>compare:
        compare = max(second)
    if compare>ans:
        ans = compare
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
input=stdin.readline
n,k=map(int,input().split())
arr=[0]+list(map(int,input().split()))
cost=[0]+list(map(int,input().split()))
ma=-10000000000000000000
for i in range(1,n+1):
    m=1
    cur=arr[i]
    co=cost[cur]
    l=[0,co]
    ma = max(ma, l[-1] * (m // k) + l[m % k])
    while(m<=k and cur!=i):
        cur=arr[cur]
        co=cost[cur]
        l.append(l[-1]+co)
        m += 1
        ma=max(ma,l[-1]*(m//k)+l[m%k])


    ma = max(ma, l[-1] * (k//m) + l[k%m])
print(ma)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

N,K=map(int,input().split())
P=tuple(map(int1,input().split()))
C=tuple(map(int,input().split()))
loop=[[-INF,0] for _ in range(N)]
used=[False]*N
for v in range(N):
    stack=[]
    d=0
    cnt=0
    while True:
        if not used[P[v]]:
            v=P[v]
            stack.append(v)
            used[v]=True
            d+=C[v]
            cnt+=1
        else:
            for vv in stack:
                loop[vv][0]=d
                loop[vv][1]=cnt
            break
ans=-INF
for i in range(N):
    d=0
    v=i
    for cnt in range(K):
        v=P[v]
        if loop[v][0]==-INF:
            d+=C[v]
            ans=max(ans,d)
        else:
            break
    loopstart=v
    v=P[i]
    MAX=-INF
    dd=0
    for ccnt in range(1,K-cnt+1):
        loopn=(K-ccnt)//loop[loopstart][1]
        if v!=i:
            dd+=C[v]
            ans=max(ans,d+dd,d+dd+loopn*loop[loopstart][0])
            v=P[v]
        else:
            break
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()))
for i in range(N):
  P[i]-=1
INF=-(10**20)
X=[[INF]*(N+1) for i in range(N)]
Y=[0]*N
Z=[0]*N
R=[0]*N
S=set()
V=0
for i in range(N):
  S=set()
  V=i
  S.add(i)
  for j in range(N):
    V=P[V]
    if V in S:
      Z[i]=V
      break
  X[i][0]=0
  for j in range(N):
    Y[i]+=1
    V=P[V]
    X[i][j+1]=X[i][j]+C[V]
    if Z[i]==V:
      R[i]=X[i][j+1]
      break
A=INF
Q=0
T=0
U=0
D=0
E=0
for i in range(N):
  D=K
  V=i
  E=0
  for j in range(min(N,K)):
    if Z[i]==V:
      break
    V=P[V]
    E+=C[V]
    D-=1
  i=V
  D,K=K,D
  if R[i]<=0:
    for j in range(1,min(Y[i],K)+1):
      A=max(A,X[i][j]+E)
  else:
    S=max((K//Y[i])-1,0)
    Q=R[i]*S
    T=0
    U=INF
    V=i
    for j in range(K-S*Y[i]):
      V=P[V]
      T+=C[V]
      U=max(T,U)
    Q+=T
    A=max(A,Q+E)
  D,K=K,D
print(A)

Submission status: Wrong Answer

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

N, K = map(int, input().split())
P = list(map(lambda x: int(x) - 1, input().split()))
C = list(map(int, input().split()))
ans = -float('inf')
for s in range(N):
    c = 0
    i = P[s]
    score = C[i]
    ans = max(ans, score)
    c += 1
    while i != s and c < K:
        i = P[i]
        score += C[i]
        ans = max(ans, score)
        c += 1
    if c == K:
        continue
    q, r = divmod(K, c)
    score *= q
    ans = max(ans, score)
    if r == 0:
        continue
    c = 0
    while c < r:
        i = P[i]
        score += C[i]
        c += 1
        ans = max(ans, score)
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = [int(hoge) for hoge in input().split()]
P = [int(hoge)-1 for hoge in input().split()]#0-indexed
C = [int(hoge) for hoge in input().split()]
LoopSum = []
ans = 0
LoopIndex = [-1 for i in range(N)]
Loops = []
num = 0
for start in range(N):
    if -1 == LoopIndex[start]:
        LpSm = C[start]
        LoopIndex[start] = num
        route = [start]
        cur = P[start]
        while cur != start:
            LoopIndex[cur] = num
            route.append(cur)
            cur = P[cur]
            LpSm += C[cur]
        Loops.append(route)
        LoopSum.append(LpSm)
        num += 1
DekiSumAmari = [(K//len(L),sum([C[j] for j in L]),K%len(L)) for L in Loops]
for s in range(N):
    Looplen =len(Loops[LoopIndex[s]])
    score = 0
    D,S,A = DekiSumAmari[LoopIndex[s]]
    if S<=0:#一周もしないほうがいい
        A = min(K,Looplen)
    else:
        if A==0:
            D -= 1
            A = Looplen
        score += D*S
    curpos = s
    curplus = 0
    maxplus = 0
    for i in range(min(K,Looplen)):
        if i == A:
            curplus -= S
        curplus += C[curpos]
        curpos = P[curpos]
        maxplus = max(maxplus,curplus)
    score += maxplus
    ans = max(ans,score)
print(ans)

Submission status: Wrong Answer

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

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

for i in range(N):
    P[i]-=1

USE=[0]*N
ANS=-1<<100
for i in range(N):
    if USE[i]==1:
        continue
    else:
        USE[i]=1
        A=[C[P[i]]]
        NOW=P[i]

        while NOW!=i:
            USE[NOW]=1
            A.append(C[P[NOW]])
            NOW=P[NOW]
            
        #print(A,NOW)

        S=sum(A)
        SCORE=0
        if S>0:
            SCORE=S*(K//len(A))
            rest=K%len(A)
        else:
            SCORE=0
            rest=min(K,len(A))

        A2=A+A+A
        S2=[0]
        for a in A2:
            S2.append(S2[-1]+a)

        restscore=-1<<100

        for i in range(len(A)):
            for j in range(i+1,i+rest+1):
                #print(i,j,S2[j]-S2[i])
                restscore=max(restscore,S2[j]-S2[i])

        #print(S2,rest,SCORE,restscore)

        ANS=max(ANS,SCORE+restscore)
print(ANS)

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 = [False] * n
from collections import deque
ds = []
sums = []
for i in range(n):
    if visited[i]: continue
    q = deque([])
    q.append(i)
    s = cs[i]
    d = [i]
    while len(q) > 0:
        u = q.popleft()
        visited[u] = True
        nx = ps[u]
        if visited[nx]: continue
        d.append(nx)
        q.append(nx)
        s += cs[nx]
    sums.append(s)
    ds.append(d)

# print(ds,sums)
from itertools import accumulate
def calcmax(d,s,k,cs):
    cnt = 0
    l = len(d)
    div, rest_ = divmod(k-1, l)
    rest_ += 1
    if s > 0:
        cnt += div*s
    d2 = d*2
    mx = - 1<<50
    c_ = [cs[j] for j in d2]
    acc = list(accumulate([0]+c_))
    for rest in range(1,rest_+1):
        for i in range(rest,l*2):
            # c = sum(c_[i-rest:i])
            c = acc[i] - acc[i-rest]
            mx = max(mx, c)
    # print(d,cnt,mx)
    return cnt + mx

ans = -1 << 50
for d,s in zip(ds,sums):
    # print("aaa",d,s)
    c = calcmax(d,s,k,cs)
    ans = max(ans,c)
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()))
ans = -10**18
for now in range(n):
	ruisekiwa = []
	tansaku = set()
	for i in range(n+1):
		targ = p[now]-1
		if len(ruisekiwa) >= 1:
			ruisekiwa.append(c[targ]+ruisekiwa[-1])
		else:
			ruisekiwa.append(c[targ])
		if targ in tansaku:
			break
		now = targ
		tansaku.add(targ)
	#print(ruisekiwa)
	if len(ruisekiwa) >= k:
		tr = max(ruisekiwa[:k])
		#print(tr)
		ans = max(ans, tr)
	else:
		if ruisekiwa[0] < ruisekiwa[-1]:
			#print(ruisekiwa[-1]-ruisekiwa[0])
			ms = (k//(len(ruisekiwa)-1))*(ruisekiwa[-1]-ruisekiwa[0])
			#print(ms)
			#print(len(ruisekiwa))
			#print(ruisekiwa[:k%(len(ruisekiwa)-1)+1])
			if k%(len(ruisekiwa)-1) >= 1:
				tr = max(max(ruisekiwa[:k%(len(ruisekiwa)-1)])+ms, max(ruisekiwa)+ms-(ruisekiwa[-1]-ruisekiwa[0]))
			else:
				tr = max(ruisekiwa)+ms-(ruisekiwa[-1]-ruisekiwa[0])
			#print(tr)
			ans = max(ans, tr)
		else:
			tr = max(ruisekiwa)
			ans = max(ans, tr)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N, K = (int(i) for i in input().split())
    P = [int(i) for i in input().split()]
    C = [int(i) for i in input().split()]

    score = [0]*(N+1)  # iから始めたときのスコア
    for i in range(1, N+1):
        s = i
        scos = [0]*(N+1)
        used = {s}
        lengt = 1
        ma = -(10**10)
        while P[s-1] not in used:
            s = P[s-1]
            scos[lengt] += scos[lengt-1] + C[s-1]
            ma = max(ma, scos[lengt])
            used.add(s)
            lengt += 1
        if K <= lengt:
            score[i] = scos[K-1]
        else:
            score[i] = scos[lengt-1]*(K//lengt) + scos[K % lengt]
            score[i] += C[i-1]*((0--K//lengt) - 1)
        score[i] = max(score[i], ma)
    print(max(score[1:]))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import time
startTimeProblem=time.time()

import fileinput, sys, itertools, functools
from math import *
from bisect import *
from heapq import *
from collections import *

def lcm(a, b):  
    return (a*b)/gcd(a, b)

class InputHelper:
    def __init__(self):
        self.myinput = fileinput.input()

    def isLocal(self):
        return not fileinput.isstdin()

    def int(self):
        return int(self.myinput.readline().rstrip())

    def ints(self):
        return [int(_) for _ in self.myinput.readline().rstrip().split()]

    def str(self):
        return self.myinput.readline().rstrip()

    def strs(self):
        return [_ for _ in self.myinput.readline().rstrip().split()]

class OutputHelper:
    def int(self, a):
        print(a)    

    def ints(self, a):  
        print(" ".join([str(_) for _ in a]))
    
    def intsNL(self, a):
        for _ in a:
            print(_)
    
    def str(self, s):
        print(s)

    def strs(self, s):
        print(" ".join([_ for _ in s]))

    def strsNL(self, s):
        for st in s:
            print(st)

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        self.prev = None

In = InputHelper()
Out = OutputHelper()

######################################

N, K = In.ints()

P = In.ints()
C = [-1] + In.ints()

connection = [-1 for i in range(N+1)]

for i in range(N):
    connection[i+1] = P[i]

ans = -99999999999

for i in range(1, N+1):
    start = connection[i]
    tempans = C[start]
    tempk = K-1

    ans = max(ans, tempans)
    seen = [False for i in range(N+1)]
    seen[start] = True    

    while tempk > 0:
        nex = connection[start]
        if not seen[nex]:
            start=nex
            seen[start]=True
            tempans += C[start]
            ans = max(ans, tempans)
            tempk-=1            
        else:
            break
    
    if tempk>N:
        if tempans<=0:
            continue
        
        
        stepsround = K-tempk
        howManyRounds = tempk//stepsround

        tempans += tempans*howManyRounds
        tempk-=howManyRounds*stepsround

        ans = max(ans, tempans)

    if tempk>0:
        seen = [False for i in range(N+1)]
        # seen[start] = True    

        while tempk > 0:
            nex = connection[start]
            if not seen[nex]:
                start=nex
                seen[start]=True
                tempans += C[start]
                ans = max(ans, tempans)
                tempk-=1            
            else:
                break



Out.int(ans)


######################################

if len(sys.argv)>2 and sys.argv[2]=="TIMEIT":
    fin = (time.time()-startTimeProblem)*1000
    print("{:.2f}".format(fin) + "ms")

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = tuple(map(lambda x: int(x)-1, input().split()))
C = tuple(map(int, input().split()))
CC = [[] for _ in range(n)]

for idx, p in enumerate(P):
    CC[idx].append(C[p])
    pp = P[p]
    for _ in range(n):
        CC[idx].append(C[pp])
        pp = P[pp]
        if pp == p:
            break
        

from itertools import accumulate
ans = -50**14
for cc in CC:
    cca = list(accumulate(cc))
    sc = sum(cc)
    if sc <= 0:
        # 1周分中のmax
        ans = max(ans, max(cca))
    else:
        kk, r = divmod(k, len(cc))
        if r == 0:
            ans = max(ans, kk*sc)
        else:
            ans = max(ans, kk * sc + max(cca[:r]))
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

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


Done = [False] * N
for i in range(N):
    if Done[i]:
        continue
    L = []
    now = i
    while True:
        L.append(C[now])
        Done[now] = True
        now = P[now] - 1
        if Done[now]:
            break
    Loop.append(L)
ans = - float('inf')
for L in Loop:
    B = [0] + list(accumulate(L + L))
    loop = K // len(L)
    rest = K % len(L)
    flag = False
    if loop > 0:
        flag = True
    ans1 = - float('inf')
    ans3 = - float('inf')
    for start in range(len(L)):
        for num in range(1, len(L)):
            end = start + num
            if end >= len(B):
                break
            if num <= rest:
                ans1 = max(ans1, B[end] - B[start])
            ans3 = max(ans3, B[end] - B[start])
    ans2 = max(0, loop * B[len(L)])
    ans4 = max(0, (loop - 1) * B[len(L)])
    ans = max(ans, ans1+ans2)
    if flag:
        ans = max(ans, ans3 + ans4)
print(ans)

Submission status: Wrong Answer

Solution code:
import collections
def main():

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

    ans = float('-inf')
    if K <= N:
        for i in range(N):
            v = 0
            k = i
            for j in range(K):
                k = P[k]-1
                v += C[k]
                ans = max(ans, v)
        return ans

    for i in range(N):
        visited = dict()
        k = i
        visited[i] = 0
        val = [0]
        v = 0
        for j in range(1, N+1):
            k = P[k] - 1
            if k not in visited:
                visited[k] = j
                val.append(C[k])
                v += C[k]
                ans = max(ans, v)
            else:
                t = j - visited[k]
                val.append(C[k])
                v += C[k]
                ans = max(ans, v)
                # print(val, j, visited[k])
                val1 = val[:visited[k]+1]
                val2 = val[visited[k]+1:]
                period = sum(val2)
                pre = sum(val1)
                if period > 0:
                    n = (K - visited[k]) // t
                    u = 0
                    max_u = 0
                    for p in range(1, (K-visited[k]) % t + 1):
                        u += val[visited[k]+p]
                        max_u = max(max_u, u)
                    ans = max(ans, u + pre + period * n)
                break


    return ans


if __name__ == '__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()))
p = [i-1 for i in p]
MINI = -10**9-1
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())


union_find = UnionFind(n)
score_map = {}
for i in range(n):
    union_find.union(i, p[i])

for root in union_find.roots():
    n_c = p[root]
    score = c[n_c]
    while n_c != root:
        n_c = p[n_c]
        score += c[n_c]
    score_map[root] = score

ans = MINI
for i in range(n):
    mx = MINI
    score = 0
    m = k
    root = union_find.find(i)
    lap_score = score_map[root]
    if lap_score > 0:
        _d = k // union_find.size(root)
        score += lap_score*_d
        mx = max(mx, score)
        m -= _d*union_find.size(root)
    else:
        m = min(k, union_find.size(root))
    if m == 0:
        ans = max(mx, ans)
        continue
    n_c = p[i]
    score += c[n_c]
    mx = max(mx, score)
    m -= 1
    while m > 0:
        n_c = p[n_c]
        score += c[n_c]
        mx = max(mx, score)
        m -= 1
    ans = max(mx, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def solve():
    ans = -inf
    for si in range(n):
        cs = [0]
        i = si
        for _ in range(k):
            i = pp[i]
            cs.append(cs[-1] + cc[i])
            if i == si: break
        cur = max(cs[1:])
        if len(cs) < k + 1:
            d = len(cs) - 1
            c = k // d
            r = k - d * c
            cur = max(cur,cs[-1] * c + max(cs[:r+1]))
        #print(cs)
        ans = max(ans, cur)
    print(ans)

inf=10**16
n,k=MI()
pp=LI1()
cc=LI()
solve()

Submission status: Wrong Answer

Solution code:
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

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

dic_s={}
dic_i={}

for i in range(1,n+1):
    if not i in dic_i:
        dic_s[i]=0
        j=i
        while not j in dic_i:
            dic_i[j]=1
            j=p[j-1]
            dic_s[i]+=1

ans=-float('inf')
for i in dic_s.keys():
    lst_p=[]
    lst_c=[]
    # print(i)
    for j in range(dic_s[i]):
        lst_p.append(p[i-1])
        i=p[i-1]
        lst_c.append(c[i-1])
    # print(lst_p)
    # print(lst_c)
    cnt=0
    sm=sum(lst_c)
    if sm>0:
        cnt+=sm*(k//dic_s[i])
        lst=lst_c+lst_c
        cnt2=-float('inf')
        for j in range(dic_s[i]):
            tmp=0
            for l in range(k%dic_s[i]):
                tmp+=lst[j+l]
                cnt2=max(cnt2,tmp)
            # print(cnt2)
        ans=max(ans,cnt+cnt2)
    else:
        lst=lst_c+lst_c
        cnt2=-float('inf')
        for j in range(dic_s[i]):
            tmp=0
            for l in range(min(k,dic_s[i])):
                tmp+=lst[j+l]
                cnt2=max(cnt2,tmp)
            # print(cnt2)
        ans=max(ans,cnt+cnt2)

print(ans)