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

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i]-1)

ma = float('INF')*(-1)
listcase = []
cc=0
for i in uf.roots():
    st = uf.members(i)[0]
    listcase.append([])
    while True:
        listcase[cc].append(c[st])
        st=p[st]-1
        if st == uf.members(i)[0]:
            break
    cc+=1

for i in listcase:
    m = len(i)
    i2=i*2
    su = 0
    if sum(i)>0:
        su = sum(i)*(k//m)
    m2 = k%m
    if m2==0 and su>0:
        m2=m
        su-=sum(i)
    elif m2==0:
        m2=m
    for l in range(m):
        dp=[float('INF')*(-1)]*(m*2)
        dp[l]=i2[l]
        for j in range(l+1,l+m2):
            dp[j]=max(dp[j-1]+i2[j],i2[j])
        ma = max(ma,su+max(dp))
print(ma)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
s = [[0] for _ in range(n)]
ans = -10**18

for i in range(n):
    flag = 0
    a = p[i]
    s[i].append(c[a-1])
    while flag == 0:
        a = p[a-1]
        if a == i + 1:
            flag = 1
        s[i].append(c[a-1]+ s[i][-1])

for i in range(n):
    a = 0
    mul = k//(len(s[i])-1)
    m = mul*(s[i][-1] > 0)
    re = k - m*(len(s[i])-1)
    a += m*s[i][-1]
    if len(s[i][1-(m!=0):min(re+1, len(s[i])-1)]):
        a += max(s[i][1-(m!=0):min(re+1, len(s[i])-1)])
    
    if a > ans:
        ans = a
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()))

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

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i]-1)

ma = float('INF')*(-1)
listcase = []
cc=0
for i in uf.roots():
    st = uf.members(i)[0]
    listcase.append([])
    while True:
        listcase[cc].append(c[st])
        st=p[st]-1
        if st == uf.members(i)[0]:
            break
    cc+=1

for i in listcase:
    m = len(i)
    i2=i*2
    su = 0
    if sum(i)>0:
        su = sum(i)*(k//m)
    m2 = k%m
    if m2==0 and su>0:
        m2=m
        su-=sum(i)
    for l in range(m):
        dp=[float('INF')*(-1)]*(m*2)
        dp[l]=i2[l]
        for j in range(l+1,l+m2):
            dp[j]=max(dp[j-1]+i2[j],i2[j])
        ma = max(ma,su+max(dp))
print(ma)

Submission status: Wrong Answer

Solution code:
n , k = 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())

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i]-1)

ma = float('INF')*(-1)
listcase = []
cc=0
for i in uf.roots():
    st = uf.members(i)[0]
    listcase.append([])
    while True:
        listcase[cc].append(c[st])
        st=p[st]-1
        if st == uf.members(i)[0]:
            break
    cc+=1

for i in listcase:
    m = len(i)
    i2=i*2
    su = 0
    if sum(i)>0:
        su = sum(i)*(k//m)
    m2 = k%m
    if m2==0:
        m2=m
        su-=sum(i)
    for l in range(m):
        dp=[float('INF')*(-1)]*(m*2)
        dp[l]=i2[l]
        for j in range(l+1,l+m2):
            dp[j]=max(dp[j-1]+i2[j],i2[j])
        ma = max(ma,su+max(dp))
print(ma)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
s = [[0] for _ in range(n)]
ans = -10**18

for i in range(n):
    flag = 0
    a = p[i]
    s[i].append(c[a-1])
    while flag == 0:
        a = p[a-1]
        if a == i + 1:
            flag = 1
        s[i].append(c[a-1]+ s[i][-1])

for i in range(n):
    a = 0
    mul = k//(len(s[i])-1)
    m = mul*(s[i][-1] > 0)
    re = k - m*(len(s[i])-1)
    a += mul*s[i][-1]
    if len(s[i][1-(m!=0):min(re+1, len(s[i])-1)]):
        a += max(s[i][1-(m!=0):min(re+1, len(s[i])-1)])
    
    if a > ans:
        ans = a
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()))

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

uf = UnionFind(n)

for i in range(n):
    uf.union(i,p[i]-1)

ma = float('INF')*(-1)
listcase = []
cc=0
for i in uf.roots():
    st = uf.members(i)[0]
    listcase.append([])
    while True:
        listcase[cc].append(c[st])
        st=p[st]-1
        if st == uf.members(i)[0]:
            break
    cc+=1

for i in listcase:
    m = len(i)
    i2=i*2
    m2 = k%m
    if m2==0:
        m2=m
    su = 0
    if sum(i)>0:
        su = sum(i)*(k//m)
    for l in range(m):
        dp=[float('INF')*(-1)]*(m*2)
        dp[l]=i2[l]
        for j in range(l+1,l+m2):
            dp[j]=max(dp[j-1]+i2[j],i2[j])
        ma = max(ma,su+max(dp))
print(ma)

Submission status: Wrong Answer

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect

n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
check=[-1]*n
finalans=-10**20
for i in range(n):
    if check[i]!=-1:
        continue
    loop=[i]
    now=i
    while p[now]!=i+1:
        check[now]=1
        loop.append(p[now]-1)
        now=p[now]-1
    L=len(loop)
    point=[0]*(L*2)
    point[0]=c[loop[0]]
    for j in range(1,L*2):
        if j<L:
            point[j]=point[j-1]+c[loop[j]]
        else:
            point[j]=point[j-1]+c[loop[j-L]]
    m=-10**20
    if point[L-1]>0:
        r=k%L
        if r==0:
            r=L
        for j in range(1,r+1):
            for t in range(j-1,j+L-1):
                cand=point[t]-point[t-j] if t-r>=0 else point[t]
                m=max(m,cand)
        ans=point[L-1]*(k//L)+m if r!=L else point[L-1]*((k//L)-1)+m
    else:
        for j in range(1,L+1):
            for t in range(j-1,j+L-1):
                cand=point[t]-point[t-j] if t-j>=0 else point[t]
                m=max(m,cand)
        ans=m
    finalans=max(ans,finalans)   
print(finalans)

Submission status: Wrong Answer

Solution code:
import sys
import resource
sys.setrecursionlimit(10000)
n,k=map(int,input().rstrip().split())
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
    if start==now:
        flag+=1
    if start==now and flag==2:
        return [max,sum,count]
    elif count==up:
        return [max,sum,count]
    else:
        count+=1
        sum+=c[p[now-1]-1]
        if max<=sum:
            max=sum
        return find(start,p[now-1],up,max,sum,count,flag)
kara=[-10000000000]
if n>k:
    for i in range(1,n+1):
        m=find(i,i,k,c[p[i-1]-1],0,0,0)
        if m[0]>kara[0]:
            kara[0]=m[0]
    result=kara[0]
else:
    for i in range(1,n+1):
        m=find(i,i,n,c[p[i-1]-1],0,0,0)
        if m[1]<=0:
            if m[0]>kara[0]:
                kara[0]=m[0]
        else:
            w=k%m[2]
            if w==0:
                w=m[2]
            spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
            if m[1]+spe>m[0] and m[1]*(k-w)//m[2]+spe>kara[0]:
                kara[0]=m[1]*(k-w)//m[2]+spe
            elif m[1]+spe<=m[0] and m[1]*((k-w)//m[2]-1)+m[0]>kara[0]:
                kara[0]=m[1]*((k-w)//m[2]-1)+m[0]
    result=kara[0]
print(result)

Submission status: Wrong Answer

Solution code:
print("A")

Submission status: Wrong Answer

Solution code:
import sys
import resource
sys.setrecursionlimit(10000)
n,k=map(int,input().rstrip().split())
p=list(map(int,input().rstrip().split()))
c=list(map(int,input().rstrip().split()))
def find(start,now,up,max,sum,count,flag):
    if start==now:
        flag+=1
    if start==now and flag==2:
        return [max,sum,count]
    elif count==up:
        return [max,sum,count]
    else:
        count+=1
        sum+=c[p[now-1]-1]
        if max<=sum:
            max=sum
        return find(start,p[now-1],up,max,sum,count,flag)
kara=[-10000000000]
if n>k:
    for i in range(1,n+1):
        kara.append(find(i,i,k,c[p[i-1]-1],0,0,0)[0])
    result=max(kara)
else:
    for i in range(1,n+1):
        m=find(i,i,n,c[p[i-1]-1],0,0,0)
        if m[1]<=0:
            if m[0]>kara[0]:
                kara[0]=m[0]
        else:
            w=k%m[2]
            if w==0:
                w=m[2]
            spe=find(i,i,w,c[p[i-1]-1],0,0,0)[0]
            if m[1]+spe>m[0] and m[1]*(k-w)//m[2]+spe>kara[0]:
                kara[0]=m[1]*(k-w)//m[2]+spe
            elif m[1]+spe<=m[0] and m[1]*((k-w)//m[2]-1)+m[0]>kara[0]:
                kara[0]=m[1]*((k-w)//m[2]-1)+m[0]
    result=kara[0]
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()))

ans = -10**9
for i in range(n):
    d = []
    d_sum = 0
    pi = p[i]
    cnt = 0
    d_max = -10**9
    while pi != p[i] or cnt == 0 or k <= cnt:
        d_sum += c[pi-1]
        # d_max = max(d_max, d_sum)
        if d_sum > d_max:
            d_max = d_sum
        d.append(d_sum)
        pi = p[pi-1]
        cnt += 1
    if k <= cnt:
        d_ans = d_max
    else:
        rp = k//cnt
        mod = k%cnt
        if mod == 0:
            d_tmp = d[-1]*rp+d_max
        else:
            d_tmp = max(d[-1]*rp+max(d[:mod]), d[-1]*(rp-1)+max(d[mod:]))
        d_ans = max(d_tmp, d_max)
    ans = max(ans, d_ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
n, k = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))


def dfs(i):
    if 0 <= visited[i]:
        return
    visited[i] = idx
    cycle.append(i)
    global csum
    csum += C[i]
    dfs(P[i])


visited = [-1]*n
idx = 0
cycles = []
for i in range(n):
    if 0 <= visited[i]:
        continue
    cycle = []
    csum = 0
    dfs(i)
    cycles.append((cycle, csum))
    idx += 1


INF = 10**18
ans = -INF
for i in range(n):
    cycle, csum = cycles[visited[i]]
    cmem = len(cycle)

    if 0 < csum:
        a, b = divmod(k, cmem)
        scoreA = csum*a
        score = 0
        scoreB = 0
        for _ in range(b):
            i = P[i]
            score += C[i]
            if scoreB < score:
                scoreB = score
        X = scoreA+scoreB
    else:
        b = min(k, cmem)
        score = 0
        INF = 10**18
        X = -INF
        for _ in range(b):
            i = P[i]
            score += C[i]
            if X < score:
                X = score

    if ans < X:
        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()))

ans = -10**9
for i in range(n):
    d = []
    d_sum = 0
    pi = p[i]
    cnt = 0
    d_max = -10**9
    while pi != p[i] or cnt == 0 or k <= cnt:
        d_sum += c[pi-1]
        d_max = max(d_max, d_sum)
        d.append(d_sum)
        pi = p[pi-1]
        cnt += 1

Submission status: Wrong Answer

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

G = [[0, 0] for _ in range(N)]
for i in range(N):
    G[i][0] = C[i]-1
    G[i][1] = P[C[i]-1]

loops = []
sums = []
for i in range(N):
    v = i
    loop = []
    total = 0
    while True:
        loop.append(v)
        total += G[v][1]
        v = G[v][0]
        if v == i:
            break

    loops.append(loop)
    sums.append(total)

max_ans = -10**9
for i, loop in enumerate(loops):
    ans = 0
    size = len(loop)
    a = K // size
    r = K % size
    if sums[i] > 0:
        ans = a * sums[i]

    tmp = G[loop[0]][1]
    if r > 0:
        for j in range(1, r):
            if G[loop[j]][1] >= 0:
                tmp += G[loop[j]][1]
            else:
                break

    ans += tmp
    if ans > max_ans:
        max_ans = ans

print(max_ans)

Submission status: Wrong Answer

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

P = [P[i]-1 for i in range(N)]
ans = -float("inf")

for start in range(N):
    x = start
    pattern = []
    while True:
        x = P[x]
        pattern.append(x)
        if x == start:
            break

    pattern_len = len(pattern)
    total = 0
    if pattern_len >= K:
        for j in range(K):
            total += C[pattern[j]]
            ans = max(ans, total)
    else:
        for j in range(pattern_len):
            total += C[pattern[j]]
        if total <= 0:
            now = 0
            for j in range(pattern_len):
                now += C[pattern[j]]
                ans = max(now, ans)
        else:
            now = 0
            now += total * (K // pattern_len)
            for j in range(K % pattern_len):
                now += C[pattern[j]]
                ans = max(ans, now)
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()))

P = [P[i]-1 for i in range(N)]
ans = -float("inf")

for start in range(N):
    x = start
    pattern = []
    while True:
        x = P[x]
        pattern.append(x)
        if x == start:
            break

    pattern_len = len(pattern)
    total = 0
    if pattern_len >= K:
        for j in range(K):
            total += C[pattern[j]]
            ans = max(ans, total)
    else:
        for j in range(pattern_len):
            total += C[pattern[j]]
        if total < 0:
            now = 0
            for j in range(pattern_len):
                now += C[pattern[j]]
                ans = max(now, ans)
        else:
            now = 0
            now += total * (K // pattern_len)
            for j in range(K % pattern_len):
                now += C[pattern[j]]
                ans = max(ans, now)
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()))

P = [P[i]-1 for i in range(N)]
ans = -float("inf")

for start in range(N):
    x = start
    pattern = []
    while True:
        x = P[x]
        pattern.append(x)
        if x == start:
            break

    pattern_len = len(pattern)
    total = 0
    if pattern_len > K:
        for j in range(K):
            total += C[pattern[j]]
            ans = max(ans, total)
    else:
        for j in range(pattern_len):
            total += C[pattern[j]]
        if total < 0:
            now = 0
            for j in range(pattern_len):
                now += C[pattern[j]]
                ans = max(now, ans)
        else:
            now = 0
            now += total * (K // pattern_len)
            for j in range(K % pattern_len):
                now += C[pattern[j]]
                ans = max(ans, now)
print(ans)

Submission status: Wrong Answer

Solution code:
"""
1. マス同士は有効グラフの一本道になっている。で、必ずどこかでループが発生している。

2. 各点から各点に移動する場合のスコアの合計とステップ数(ループ内の場合は一周以内のもの)を前処理(dfs)で求めておく。dp[i][j] => iからjまでのスコアとステップ数

3. K > N の場合、ループを通るとスコアがマイナスになるなら（dp[i][i]がマイナスになるようなiが存在するなら）、ループを一周しない方がよい。
ループを通るとスコアがプラスになるなら、

各iに対して地点iからスタートする場合というのをシミュレートすると実装が楽そう。
K <= Nの場合はi番目からスタートして、dfsでstep数がKに到達するまで進み続けて、スコアの最大値を図る。
Kが大きい場合は、dfsで道をたどっていってループを検出したら、その時点でループスコアがマイナスかプラスかを判断して、マイナスなら終了。
プラスならループスコア*(K//ループstep)を加算してできる限りKを減らす。そこからstep数がKに到達するまでdfsで道をたどっていって最大値を求める。
各スタート地点ごとにO(N)で処理可能なので、全体ではO(N^2)で処理できる
"""
N,K = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))

ans = -float("INF")
for i in range(1,N+1):
    scores = [None]*(N+1)
    steps = [None]*(N+1)
    step = 0
    cur = i
    score = 0
    loopFlag = False
    while step <= K:
        if scores[cur]!=None and not loopFlag:
            loopFlag = True
            loopScore = score - scores[cur]
            loopStep = step - steps[cur]
            score += ((K-step)//loopStep)*loopScore
            step += ((K-step)//loopStep)*loopStep
        scores[cur] = score
        steps[cur] = step
        if step != 0:
            ans = max(ans,score)
        p = P[cur-1]
        c = C[p-1]
        cur = p
        score += c
        step += 1

print(ans)

Submission status: Wrong Answer

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

points = list()
for i in range(N):
    sum = 0
    now = P[i]
    result = list()
    flag = True
    for j in range(N):
        sum += C[now]
        result.append(sum)
        if now == i:
            break
        if j == N-1 and now != i:
            flag = False
        now = P[now]

    if flag:
        points.append(result)
    else:
        # iスタートでiに戻るループが存在しない
        points.append([-int(1e19)])

ans = -int(1e19)

for i in range(len(points)):
    now = i
    tmpp = 0
    k = K
    while points[now][0] == -int(1e19):
        now = P[now]
        tmpp += C[now]
        k -= 1
        ans = max(ans, tmpp)

    cir = len(points[now])
    cir_point = points[now][cir-1]

    if k <= cir:
        for j in range(k):
            ans = max(ans, points[now][j] + tmpp)
    else:
        if cir_point > 0:
            for j in range(k % cir):
                ans = max(ans, points[now][j] + (k // cir) * cir_point + tmpp)

        for j in range(cir):
            ans = max(ans, points[now][j] + tmpp)

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()))
#memo = [[0]*(n+1)for _ in range(n+1)]
#for i in range(1,n+1):
    #memo[i][0] = [i,0]

to_do = []
res = -float('inf')
for i in range(1,n+1):
    tmp_idx = i
    tmp_val = 0
    tmp_dic = {i:(0,0,i)}
    for j in range(1,min(n+1,k+1)):
        #tmp_idx,tmp_val = ps[memo[i][j-1][0]-1],memo[i][j-1][1]+cs[ps[memo[i][j-1][0]-1]-1]
        #memo[i][j] = [tmp_idx,tmp_val]
        tmp_idx = ps[tmp_idx-1]
        tmp_val += cs[tmp_idx-1]
        res = max(res,tmp_val)
        if tmp_idx not in tmp_dic:
            tmp_dic[tmp_idx] = (j,tmp_val,tmp_idx)
        else:
            if tmp_val >= tmp_dic[tmp_idx][1]:
                to_do.append([i,tmp_dic[tmp_idx][0],tmp_dic[tmp_idx][2],tmp_dic[tmp_idx][1],j-tmp_dic[tmp_idx][0],tmp_val-tmp_dic[tmp_idx][1]])
            #break

for do in to_do:
    itr = (k - do[1]) // do[4]
    remain = k - do[1] - do[4] * itr
    tmp_res = do[3] + itr * do[5]
    res = max(res,tmp_res)
    now = do[2]
    for i in range(remain):
        now = ps[now-1]
        tmp_res += cs[now-1]
        res = max(res, tmp_res)
print(res)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
ps = list(map(int, input().split()))
cs = list(map(int, input().split()))
#memo = [[0]*(n+1)for _ in range(n+1)]
#for i in range(1,n+1):
    #memo[i][0] = [i,0]

to_do = []
res = -float('inf')
for i in range(1,n+1):
    tmp_idx = i
    tmp_val = 0
    tmp_dic = {i:(0,0,i)}
    for j in range(1,min(n+1,k+1)):
        #tmp_idx,tmp_val = ps[memo[i][j-1][0]-1],memo[i][j-1][1]+cs[ps[memo[i][j-1][0]-1]-1]
        #memo[i][j] = [tmp_idx,tmp_val]
        tmp_idx = ps[tmp_idx-1]
        tmp_val += cs[tmp_idx-1]
        res = max(res,tmp_val)
        if tmp_idx not in tmp_dic:
            tmp_dic[tmp_idx] = (j,tmp_val,tmp_idx)
        else:
            if tmp_val > tmp_dic[tmp_idx][1]:
                to_do.append([i,tmp_dic[tmp_idx][0],tmp_dic[tmp_idx][2],tmp_dic[tmp_idx][1],j-tmp_dic[tmp_idx][0],tmp_val-tmp_dic[tmp_idx][1]])
            break

for do in to_do:
    itr = (k - do[1]) // do[4]
    remain = k - do[1] - do[4] * itr
    tmp_res = do[3] + itr * do[5]
    res = max(res,tmp_res)
    now = do[2]
    for i in range(remain):
        now = ps[now-1]
        tmp_res += cs[now-1]
        res = max(res, tmp_res)
print(res)

Submission status: Wrong Answer

Solution code:
import itertools
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_right(self, p, v):  # apply operator from the right side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(dat[p], v)
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def operate_left(self, p, v):  # apply operator from the left side
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = f(v, dat[p])
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        vl = vr = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                vl = f(vl, dat[l])
                l += 1
            if r & 1:
                r -= 1
                vr = f(dat[r], vr)
            l >>= 1
            r >>= 1
        return f(vl, vr)


ans = -float('inf')
se = set()
for start in range(N):
    if start in se:
        continue
    now = start
    scores = []
    while True:
        if now in se:
            break
        se.add(now)
        scores += [C[now]]
        now = P[now]
    cyclelen = len(scores)
    cycle, residue = divmod(K, cyclelen)
    scores *= 2
    scores = list(itertools.accumulate(scores))
    st = SegmentTree(scores, max, -float('inf'))
    ans = max([ans] + [
        st.query(start2 + 1, start2 + min(K + 1, cyclelen)) - scores[start2]
        for start2 in range(cyclelen)
    ])
    scorelastcycle = scores[-1] * cycle // 2
    if scorelastcycle > 0 and cycle > 0:
        d = 0
        for start2 in range(cyclelen):
            d = max(d, st.query(start2, start2 + residue + 1) - scores[start2])
        scorelastcycle += d
        ans = max(ans, scorelastcycle)
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**9
for i in range(n):
    d = []
    d_sum = 0
    pi = p[i]
    rp = 0
    while pi != p[i] or rp == 0:
        d_sum += c[pi-1]
        # d_max = max(d_max, d_sum)
        d.append(d_sum)
        pi = p[pi-1]
        rp += 1
    # print(d)
    # print(d_max)
    if k <= rp:
        d_max = max(d[:k+1])
    else:
        cnt = k//rp
        mod = k%rp
        if mod == 0:
            d_max = d[-1]*cnt+max(d)
        else:
            d_max = max(d[-1]*cnt+max(d[:mod]), d[-1]*(cnt-1)+max(d[mod:]))
        d_max = max(d_max, max(d))
    ans = max(ans, d_max)
print(ans)