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=map(int,input().split())
Plist=list(map(int,input().split()))
Clist=list(map(int,input().split()))
roopindexes=[0]*N
roops=[]
maxlist=[]
roopindex=0
for i in range(N):
    if not roopindexes[i]: #ループに含まれない
        roopindex+=1
        roops.append([])
        while not roopindexes[i]: #一周目である
            roops[-1].append(i)
            roopindexes[i]=roopindex
            i=Plist[i]-1
rindexmax=roopindex
for ind in range(rindexmax):
    sumation=0
    for index in roops[ind]:
        sumation+=Clist[index]
    maxi=-10**18
    if K>=len(roops[ind]):
        if sumation>0:
            for start in range(len(roops[ind])):
                total=0
                for time in range(K%len(roops[ind])):
                    total+=Clist[roops[ind][start+time-len(roops[ind])]]
                    maxi=max(maxi,total)
            maxi+=sumation*(K//len(roops[ind]))
        else:
            for start in range(len(roops[ind])):
                total=0
                for time in range(len(roops[ind])):
                    total+=Clist[roops[ind][start+time-len(roops[ind])]]
                    maxi=max(maxi,total)
    else:
        for start in range(len(roops[ind])):
            total=0
            for time in range(K):
                total+=Clist[roops[ind][start+time-len(roops[ind])]]
                maxi=max(maxi,total)
    maxlist.append(maxi)
print(max(maxlist))

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
Plist=list(map(int,input().split()))
Clist=list(map(int,input().split()))
roopindexes=[0]*N
roops=[]
maxlist=[]
roopindex=0
for i in range(N):
    if not roopindexes[i]: #ループに含まれない
        roopindex+=1
        roops.append([])
        while not roopindexes[i]: #一周目である
            roops[-1].append(i)
            roopindexes[i]=roopindex
            i=Plist[i]-1
rindexmax=roopindex
for ind in range(rindexmax):
    sumation=0
    for index in roops[ind]:
        sumation+=Clist[ind]
    maxi=0
    if K>=len(roops[ind]):
        if sumation>0:
            for start in range(len(roops[ind])):
                total=0
                for time in range(K%len(roops[ind])):
                    total+=Clist[roops[ind][start+time-len(roops[ind])]]
                    maxi=max(maxi,total)
            maxi+=sumation*(K//len(roops[ind]))
            print('a')
        else:
            for start in range(len(roops[ind])):
                total=0
                for time in range(len(roops[ind])):
                    total+=Clist[roops[ind][start+time-len(roops[ind])]]
                    maxi=max(maxi,total)
            print('b')
    else:
        for start in range(len(roops[ind])):
            total=0
            for time in range(K):
                total+=Clist[roops[ind][start+time-len(roops[ind])]]
                maxi=max(maxi,total)
        print('c')
    maxlist.append(maxi)
print(max(maxlist))

Submission status: Wrong Answer

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

def get(pos):
    used = [-1] * N
    cost = [0] * (N+1)

    for k in range(N+1):
        if k:
            cost[k] = cost[k-1] + C[pos]
        if used[pos] >= 0:
            loop_size = k-used[pos]
            break
        used[pos] = k
        pos = P[pos] - 1
    if cost[loop_size] <= 0 or K <= loop_size:
        return max(cost[1:K+1])
    else:
        return cost[loop_size] * (K//loop_size) + max(cost[:(K%loop_size)+1])

ans = max([get(i) for i in range(N)])
print(ans)

Submission status: Wrong Answer

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

def get(pos):
    used = [-1] * N
    cost = [0] * (N+1)

    for k in range(N+1):
        if k:
            cost[k] = cost[k-1] + C[pos]
        if used[pos] >= 0:
            loop_size = k-used[pos]
            break
        used[pos] = k
        pos = P[pos] - 1

    return max(cost[1:K+1]) if cost[loop_size] <= 0 else cost[loop_size] * (K//loop_size) + max(cost[:(K%loop_size)+1])

ans = max([get(i) for i in range(N)])
print(ans)

Submission status: Wrong Answer

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

def get(pos):
    used = [-1] * N
    cost = [0] * (N+1)

    for k in range(N+1):
        if k:
            cost[k] = cost[k-1] + C[pos]
        if used[pos] >= 0:
            loop_size = k-used[pos]
            break
        used[pos] = k
        pos = P[pos] - 1

    return max(cost[1:K+1]) if cost[loop_size] < 0 else cost[loop_size] * (K//loop_size) + max(cost[:(K%loop_size)+1])

ans = max([get(i) for i in range(N)])
print(ans)

Submission status: Wrong Answer

Solution code:
# ABC175 D
import bisect

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

F=[0]*N

def search(n):
    res=[]
    l=0
    m=n
    tmp_res=0
    loop=0
    while 1:
        m=P[m-1]
        tmp_res+=C[m-1]
        l+=1
        res.append((tmp_res,l))
        if m==n:
            loop=1
            break
        if l==K:
            break
    if loop:
        s=res[-1][0]
    else:
        s=-1
    p=max([p+s*(K-k)//len(res) if s>0 and K>=k else p for p,k in res])
    return p

res=-float('inf')
for i in range(N):
    res=max(res,search(i+1))
print(res)

Submission status: Wrong Answer

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

def get(pos):
    used = [-1] * N
    cost = [0] * (N+1)
    loop_size = 0

    for k in range(N+1):
        if k:
            cost[k] = cost[k-1] + C[pos]
        if used[pos] >= 0:
            loop_size = k-used[pos]
            break
        used[pos] = k
        pos = P[pos] - 1

    if cost[loop_size] < 0:
        v = max(cost[1:K+1])
    else:
        v = cost[loop_size] * (K//loop_size) + max(cost[:(K%loop_size)+1])
    return v

ans = max([get(i) for i in range(N)])
print(ans)

Submission status: Wrong Answer

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

def get(pos):
    used = [-1] * N
    cost = [0] * (N+1)
    loop_size = 0

    for k in range(N+1):
        if k:
            cost[k] = cost[k-1] + C[pos]
        if used[pos] >= 0:
            loop_size = k-used[pos]
            break
        used[pos] = k
        pos = P[pos] - 1

    if cost[loop_size] < 0 or loop_size==0:
        v = max(cost[1:K+1])
    else:
        v = cost[loop_size] * (K//loop_size) + max(cost[:(K%loop_size)+1])
    return v

ans = max([get(i) for i in range(N)])
print(ans)

Submission status: Wrong Answer

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

def get(pos):
    used = [-1] * N
    cost = [0] * (N+1)
    loop_size = 0

    for k in range(N+1):
        if k:
            cost[k] = cost[k-1] + C[pos]
        if used[pos] >= 0:
            loop_size = k-used[pos]
            break
        used[pos] = k
        pos = P[pos] - 1

    if cost[loop_size] < 0 or loop_size==0:
        v = max(cost[1:K+1])
    else:
        v = cost[loop_size] * (K//loop_size) + max(cost[:(K%loop_size)+1])
    return v

ans = max(get(i) for i in range(N))
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
n,k = map(int,stdin.readline().split())
p = list(map(int,stdin.readline().split()))
c = list(map(int,stdin.readline().split()))

ans = -float("inf")
def helper(index):
    visited  = {index}
    looplen = 1
    looptotal = c[index]
    while p[index]-1 not in visited:
        nextindex = p[index] - 1
        looplen += 1
        looptotal += c[nextindex]
        visited.add(nextindex)
        index = nextindex
    return (looplen,looptotal)

for i in range(n):
    looplen,looptotal = helper(i)
    if looptotal >= 0:
        cur = looptotal*(k//looplen)
    else:
        cur = 0
    curmax = -float("inf")
    remain = k%looplen if k%looplen else looplen
    curindex = i
    for _ in range(remain):
        nextindex = p[curindex]-1
        cur += c[nextindex]
        curmax = max(curmax,cur)
        curindex = nextindex
    ans = max(ans,curmax)
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
n,k = map(int,stdin.readline().split())
p = list(map(int,stdin.readline().split()))
c = list(map(int,stdin.readline().split()))

ans = -float("inf")
def helper(index):
    visited  = {index}
    looplen = 1
    looptotal = c[index]
    while p[index]-1 not in visited:
        nextindex = p[index] - 1
        looplen += 1
        looptotal += c[nextindex]
        visited.add(nextindex)
        index = nextindex
    return (looplen,looptotal)

for i in range(n):
    looplen,looptotal = helper(i)
    if looptotal >= 0:
        cur = looptotal*(k//looplen)
    else:
        cur = 0
    curmax = cur
    remain = k%looplen
    curindex = i
    for _ in range(remain):
        nextindex = p[curindex]-1
        cur += c[nextindex]
        curmax = max(curmax,cur)
        curindex = nextindex
    ans = max(ans,curmax)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.readline
import time
from heapq import heappush, heappop, heapify
import math
from math import gcd
import itertools as it
from collections import deque 

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

INF = 1001001001

# ---------------------------------------

n, k = inpl()
p = [0] + inpl()
c = [0] + inpl()

ans = - INF

for i in range(1, n + 1):
    loop = 0
    nxt = p[i]
    cost = [0]
    for j in range(1, k + 1):
        loop += c[nxt]
        ans = max(ans, loop)
        nxt = p[nxt]
        cost.append(loop)
        if nxt == p[i]:
            if loop > 0:
                cnt = k % j
                score = loop + (k // j)
                ans = max(ans, score + cost[k % j])
            break
            # if loop <= 0:
            #     break
            # else:
            #     score = loop * (k // j)
            #     score2 = 0
            #     for l in range(k % j):
            #         score2 += c[nxt]
            #         nxt = p[nxt]
            #         score = max(score, score + score2)
            #     ans = max(ans, score)
            #     break
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.readline
import time
from heapq import heappush, heappop, heapify
import math
from math import gcd
import itertools as it
from collections import deque 

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

INF = 1001001001

# ---------------------------------------

n, k = inpl()
p = [0] + inpl()
c = [0] + inpl()

ans = - INF

for i in range(1, n + 1):
    loop = 0
    nxt = p[i]
    cost = [0]
    for j in range(1, k + 1):
        loop += c[nxt]
        ans = max(ans, loop)
        nxt = p[nxt]
        cost.append(loop)
        if nxt == p[i]:
            if loop > 0:
                cnt = k % j
                score = loop + (k // j)
                ans = max(ans, score + cost[k % j])
            # if loop <= 0:
            #     break
            # else:
            #     score = loop * (k // j)
            #     score2 = 0
            #     for l in range(k % j):
            #         score2 += c[nxt]
            #         nxt = p[nxt]
            #         score = max(score, score + score2)
            #     ans = max(ans, score)
            #     break
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.readline
import time
from heapq import heappush, heappop, heapify
import math
from math import gcd
import itertools as it
from collections import deque 

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

INF = 1001001001

# ---------------------------------------

n, k = inpl()
p = [0] + inpl()
c = [0] + inpl()

ans = - INF

for i in range(1, n + 1):
    loop = 0
    nxt = p[i]
    for j in range(1, k + 1):
        loop += c[nxt]
        ans = max(ans, loop)
        nxt = p[nxt]
        if nxt == p[i]:
            if loop <= 0:
                break
            else:
                score = loop * (k // j)
                score2 = 0
                for l in range(k % j):
                    score2 += c[nxt]
                    nxt = p[nxt]
                    score = max(score, score + score2)
                ans = max(ans, score)
                break
print(ans)

Submission status: Wrong Answer

Solution code:
# ABC175 D
import bisect

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

F=[0]*N

def search(n):
    res=[]
    l=0
    m=n
    tmp_res=0
    while 1:
        m=P[m-1]
        tmp_res+=C[m-1]
        l+=1
        res.append((tmp_res,l))
        if m==n or l==K:
            break
    p,k=max(res)
    s=res[-1][0]
    if s>0 and K>=k:
        p+=s*(K-k)//len(res)
    return p

res=-float('inf')
for i in range(N):
    res=max(res,search(i+1))
print(res)

Submission status: Wrong Answer

Solution code:
# ABC175 D
import bisect

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

F=[0]*N

def search(n):
    res=[]
    l=0
    m=n
    tmp_res=0
    while 1:
        m=P[m-1]
        tmp_res+=C[m-1]
        l+=1
        res.append((tmp_res,l))
        if m==n:
            break
    p,k=max(res)
    s=res[-1][0]
    if s>0:
        p+=s*(K-k)//len(res)
    return p

res=-float('inf')
for i in range(N):
    res=max(res,search(i+1))
print(res)

Submission status: Wrong Answer

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

movement = 0
score = 0
result = []

for i in P:
    place = i
    while movement < K:
        score += C[place - 1]
        movement += 1
        place = P[i - 1]
        result.append(score)
    score = 0
    movement = 0

print(max(result))

Submission status: Wrong Answer

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

    max_score = max(C)
    score = [0]*N
    for _ in range(K):
        score = [score[i]+C[num-1] for i, num in enumerate(P)]
        max_score = max(score) if max_score < max(score) else max_score
        P = [P[i-1] for i in P]

    print(max_score)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
*p,=map(int, input().split())
for i in range(n):
    p[i]-=1
*c,=map(int, input().split())
scr=max(c)
if scr<0:
    print(scr)
    exit()
used=[0]*n

cyc=[]

for i in range(n):
    if used[i]:
        continue
    tmp=i
    cyci=[i]
    used[i]=1
    while not used[p[tmp]]:
        tmp=p[tmp]
        cyci.append(tmp)
        used[tmp]=1
    cyc.append(cyci)

for cyci in cyc:
    loop=0
    for j in cyci:
        loop+=c[j]
        #loopは負だが途中が大きくなる場合
        #たぶんまだ不足なのでサイクル1回で済ませないほうがよい
        scr=max(scr,loop)
    lc=len(cyci)
    lps=k//lc
    tmp=loop*lps

    rmk=k%lc
    #途中で打ち切ったほうがいいかもしれない
    if rmk%lc==0:
        rmk+=lc
        tmp-=loop
        lps-=1
    if lps:
        rmk+=lc
        tmp-=loop
    #あまり
    rm_mx=0
    for j in range(lc):
        tmp2=0
        for l in range(rmk):
            tmp2+=c[cyci[(j+l)%lc]]
            rm_mx=max(rm_mx,tmp2)
    tmp+=rm_mx
    scr=max(scr,tmp)
print(scr)

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
*p,=map(int, input().split())
for i in range(n):
    p[i]-=1
*c,=map(int, input().split())
scr=max(c)
if scr<0:
    print(scr)
    exit()
used=[0]*n

cyc=[]

for i in range(n):
    if used[i]:
        continue
    tmp=i
    cyci=[i]
    used[i]=1
    while not used[p[tmp]]:
        tmp=p[tmp]
        cyci.append(tmp)
        used[tmp]=1
    cyc.append(cyci)
#1kaiidou


for cyci in cyc:
    loop=0
    for j in cyci:
        loop+=c[j]
    lc=len(cyci)
    lps=k//lc
    tmp=loop*(k//lc)

    rmk=k%lc
    #途中で打ち切ったほうがいいかもしれない
    if rmk%lc==0:
        rmk+=lc
        tmp-=loop
        lps-=1
    if lps:
        rmk+=lc
        tmp-=loop
    
            
    #あまり
    rm_mx=0
    for j in range(lc):
        tmp2=0
        for l in range(rmk):
            tmp2+=c[cyci[(j+l)%lc]]
            rm_mx=max(rm_mx,tmp2)
    tmp+=rm_mx
    scr=max(scr,tmp)
print(scr)

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
*p,=map(int, input().split())
for i in range(n):
    p[i]-=1
*c,=map(int, input().split())
if max(c)<0:
    print(max(c))
    exit()
used=[0]*n

cyc=[]

for i in range(n):
    if used[i]:
        continue
    tmp=i
    cyci=[i]
    used[i]=1
    while not used[p[tmp]]:
        tmp=p[tmp]
        cyci.append(tmp)
        used[tmp]=1
    cyc.append(cyci)
#1kaiidou
scr=max(c)

for cyci in cyc:
    loop=0
    for j in cyci:
        loop+=c[j]
    lc=len(cyci)
    tmp=loop*(k//lc)

    rmk=k%lc
    #途中で打ち切ったほうがいいかもしれない
    if k//lc:
        rmk+=lc
        tmp-=loop
        if rmk%lc==0 and k//lc>1:
            rmk+=lc
            tmp-=loop
            
    #あまり
    rm_mx=0
    for j in range(lc):
        tmp2=0
        for l in range(rmk):
            tmp2+=c[cyci[(j+l)%lc]]
            rm_mx=max(rm_mx,tmp2)
    tmp+=rm_mx
    scr=max(scr,tmp)
print(scr)

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
*p,=map(int, input().split())
for i in range(n):
    p[i]-=1
*c,=map(int, input().split())
if max(c)<0:
    print(max(c))
    exit()
used=[0]*n

cyc=[]

for i in range(n):
    if used[i]:
        continue
    tmp=i
    cyci=[i]
    used[i]=1
    while not used[p[tmp]]:
        tmp=p[tmp]
        cyci.append(tmp)
        used[tmp]=1
    cyc.append(cyci)
#1kaiidou
scr=max(c)

for cyci in cyc:
    loop=0
    for j in cyci:
        loop+=c[j]
    lc=len(cyci)
    tmp=loop*(k//lc)

    rmk=k%lc
    #途中で打ち切ったほうがいいかもしれない
    if k//lc:
        rmk+=lc
        tmp-=loop
    #あまり
    rm_mx=0
    for j in range(lc):
        tmp2=0
        for l in range(rmk):
            tmp2+=c[cyci[(j+l)%lc]]
            rm_mx=max(rm_mx,tmp2)
    tmp+=rm_mx
    scr=max(scr,tmp)
print(scr)

Submission status: Wrong Answer

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

used=[0]*n

cyc=[]

for i in range(n):
    if used[i]:
        continue
    tmp=i
    cyci=[i]
    used[i]=1
    while not used[p[tmp]]:
        tmp=p[tmp]
        cyci.append(tmp)
        used[tmp]=1
    cyc.append(cyci)
#1kaiidou
scr=max(c)

for cyci in cyc:
    loop=0
    for j in cyci:
        loop+=c[j]
    lc=len(cyci)
    tmp=loop*(k//lc)

    rmk=k%lc
    #途中で打ち切ったほうがいいかもしれない
    if k//lc:
        rmk+=lc
        tmp-=loop
    #あまり
    rm_mx=0
    for j in range(lc):
        tmp2=0
        for l in range(rmk):
            tmp2+=c[cyci[(j+l)%lc]]
            rm_mx=max(rm_mx,tmp2)
    tmp+=rm_mx
    scr=max(scr,tmp)
print(scr)

Submission status: Wrong Answer

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

result = -float('inf')
for i in range(N):
    p = P[i] - 1
    c = C[p]
    k = K - 1
    t = c
    while p != i and k != 0:
        p = P[p] - 1
        c += C[p]
        t = max(t, c)
        k -= 1
    if k == 0 or c <= 0:
        result = max(result, t)
        continue
    l = K - k
    c = c * (K // l)
    k = K - (K // l) * l
    t = c
    while k != 0:
        p = P[p] - 1
        c += C[p]
        t = max(t, c)
        k -= 1
    result = max(result, t)
print(result)

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 = min(c)

for i in range(n):
	num = i
	point = 0
	for _ in range(k):
		num = p[num] - 1
		point += c[p[num]-1]
		num = p[p[num]-1] - 1
		if point > max: max = point

print(max)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
point_start_with = [0 for i in range(n)]
roop_count = [1 for i in range(n)]
for i in range(n):
    now = (i + 1)
    now_score = 0
    while p[now - 1] != (i + 1):
        now = p[now - 1]
        now_score += c[now - 1]
        roop_count[i] += 1
    point_start_with[i] = now_score
# 多分0でいい
ans = -(10**9 * 5000)
for i in range(n):
    # iからスタートする場合
    score = 0
    remain_move = 0
    cand_score = 0
    if point_start_with[i] + c[i] > 0 and k > roop_count[i]:
        # 一周以上する可能性がある場合
        # n週して、残りの動ける回数
        # print("Yes")
        round_count = (k // roop_count[i]) - 1
        remain_move = k - round_count * roop_count[i]
        cand_score = round_count * ( point_start_with[i] + c[i] )
    else:
        remain_move = roop_count[i]
        score = -(10**9 * 5000)
        cand_score = 0
    now = i
    for j in range(remain_move):
        now = p[now] - 1
        cand_score += c[now]
        score = max(score, cand_score)
    # print("start : {}  score : {}".format(i,score))
    ans = max(score, ans)
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()))

c_list = []
rink_list = []
visited = set()

for i in range(n):
    if i in visited:
        continue

    rink = [i]
    visited.add(i)
    j = p[i] - 1
    while not j in visited:
        visited.add(j)
        rink.append(j)
        j = p[j] - 1

    rink_list.append(rink)

# print(rink_list)
ans = -10 ** 20
for rink in rink_list:
    maxcost = -10 ** 20
    sum_c = 0
    for i in rink:
        sum_c += c[i]
    for i in range(len(rink)):
        j = i + 1
        if j >= len(rink):
            j = 0
        # tmp = c[rink[i]]
        tmp = 0
        cnt = 0
        while cnt <= k and i != j:
            cnt += 1

            tmp += c[rink[j]]
            maxcost = max(maxcost, tmp, tmp + sum_c * ((k - cnt) // len(rink)))
            j += 1
            if j >= len(rink):
                j = 0

    # maxcost = max(maxcost, maxcost + sum_c * (k // len(rink)))
    ans = max(ans, maxcost)

if ans == 0:
    ans = max(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()))

c_list = []
rink_list = []
visited = set()

for i in range(n):
    if i in visited:
        continue

    rink = [i]
    visited.add(i)
    j = p[i] - 1
    while not j in visited:
        visited.add(j)
        rink.append(j)
        j = p[j] - 1

    rink_list.append(rink)

# print(rink_list)
ans = -10 ** 20
for rink in rink_list:
    maxcost = -10 ** 20
    sum_c = 0
    for i in rink:
        sum_c += c[i]
    for i in range(len(rink)):
        j = i + 1
        if j >= len(rink):
            j = 0
        # tmp = c[rink[i]]
        tmp = 0
        maxcost = max(maxcost, tmp)
        cnt = 0
        while cnt < k and i != j:
            cnt += 1

            # print(i, j)
            # print(rink, i, j)
            tmp += c[rink[j]]
            maxcost = max(maxcost, tmp, tmp + sum_c * ((k - cnt) // len(rink)))
            j += 1
            if j >= len(rink):
                j = 0

    # maxcost = max(maxcost, maxcost + sum_c * (k // len(rink)))
    ans = max(ans, maxcost)

if ans == 0:
    ans = max(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()))

c_list = []
rink_list = []
visited = set()

for i in range(n):
    if i in visited:
        continue

    rink = [i]
    visited.add(i)
    j = p[i] - 1
    while not j in visited:
        visited.add(j)
        rink.append(j)
        j = p[j] - 1

    rink_list.append(rink)

# print(rink_list)
ans = -10 ** 20
for rink in rink_list:
    maxcost = -10 ** 20
    for i in range(len(rink)):
        j = i + 1
        if j >= len(rink):
            j = 0
        # tmp = c[rink[i]]
        tmp = 0
        maxcost = max(maxcost, tmp)
        cnt = 0
        while cnt < k % len(rink) and i != j:
            cnt += 1

            # print(i, j)
            # print(rink, i, j)
            tmp += c[rink[j]]
            maxcost = max(maxcost, tmp)
            j += 1
            if j >= len(rink):
                j = 0

    sum_c = 0
    for i in rink:
        sum_c += c[i]

    maxcost = max(maxcost, maxcost + sum_c * (k // len(rink)))
    ans = max(ans, maxcost)

if ans == 0:
    ans = max(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()))

c_list = []
rink_list = []
visited = set()

for i in range(n):
    if i in visited:
        continue

    rink = [i]
    visited.add(i)
    j = p[i] - 1
    while not j in visited:
        visited.add(j)
        rink.append(j)
        j = p[j] - 1

    rink_list.append(rink)

# print(rink_list)
ans = -10 ** 20
for rink in rink_list:
    maxcost = -10 ** 20
    for i in range(len(rink)):
        j = i + 1
        if j >= len(rink):
            j = 0
        # tmp = c[rink[i]]
        tmp = 0
        maxcost = max(maxcost, tmp)
        while j - i <= (k % len(rink)) and i != j:
            if i < j and j - i > k % len(rink):
                break
            if j < i and j + len(rink) - i > k % len(rink):
                break
            # print(i, j)
            # print(rink, i, j)
            tmp += c[rink[j]]
            maxcost = max(maxcost, tmp)
            j += 1
            if j >= len(rink):
                j = 0

    sum_c = 0
    for i in rink:
        sum_c += c[i]
    # print(sum_c, maxcost, (k // len(rink)))
    maxcost = max(maxcost, maxcost + sum_c * (k // len(rink)))
    # print(maxcost, sum_c, (k // len(rink)))
    ans = max(ans, maxcost)

if ans == 0:
    ans = max(c)
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
N, K = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
k_max = 5001
score = [0] * N

for i in range(N):
  exist_i = [(False, -1)] * k_max # (exist, j)
  exist_i[i] = (True, 0)
  score_i = [-10**9-1] * k_max # iからスタートしてK回操作する場合の累積和
  score_i[0] = C[P[i]-1]
  index = P[i]-1
  for j in range(1, K):
    if exist_i[index][0] == True:
      # 既に進んだことがあるマスの場合
      
      # ループ終了インデックスからループ開始インデックスの累積和の差を確認
      loop_score = score_i[j-1]
      if exist_i[index][1] != 0:
        loop_score = score_i[j-1] - score_i[exist_i[index][1] - 1] # 1ループで増えるスコア
#      print("i, j, score_i", i, j, score_i)
#      print("i, j, loop_score", i, j, loop_score)
      if loop_score > 0:
        loop_num = j - exist_i[index][1] # ループする要素数
        num = K-j # 残りの操作数
        tmp_score = score_i[j-1] + num // loop_num * loop_score # ループ前までの累積和
#        print("i, j, tmp_score", i, j, tmp_score)
        tmp_array = [0] * (num % loop_num + 1)
        tmp_array[0] = tmp_score
        for l in range(1, num % loop_num + 1):
          tmp_array[l] = tmp_array[l-1] + C[P[index]-1]
          index = P[index]-1
#        print("i, j, tmp_array", i, j, tmp_array)
        score[i] = max(tmp_array)
      else:
#        print("i, j, score_i", i, j, score_i)
        score[i] = max(score_i)
#      print("i, j, score_i", i, j, score_i)
      break
    else:
      if j == K-1:
        score_i[j] = score_i[j-1] + C[P[index]-1]
        score[i] = max(score_i)
#        print("i, j, score_i", i, j, score_i)
        break   
    score_i[j] = score_i[j-1] + C[P[index]-1]
#    print("i, j, score_i", i, j, score_i)
#    print("i, j, score", i, j, score)
    exist_i[index] = (True, j)
    index = P[index]-1
print(max(score))