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:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n, k = MAP()
p = LIST()
c = LIST()

for i in range(n):
    p[i] -= 1

ans = -inf
for i in range(n):
    visit = [inf]*n
    reg_score = [-inf]*n

    now = i
    count = 0
    score = 0
    while visit[now] == inf:
        visit[now] = count
        reg_score[now] = score
        count += 1
        now = p[now]
        score += c[now]

    x = visit[now]
    y = count - visit[now]
    X = reg_score[now]
    Y = score - reg_score[now]

    for j in range(n):
        if visit[j] == inf:
            continue
        if j != i:
            tmp0 = reg_score[j]
            if ( k - x ) % y >= visit[j]:
                tmp1 = (k - x)//y * Y + reg_score[j]
            else:
                tmp1 = ((k - x)//y - 1) * Y + reg_score[j]
            ans = max(ans, tmp0, tmp1)
        elif (k-x)//y>0:
            tmp0 = Y + reg_score[j]
            if ( k - x ) % y >= visit[j]:
                tmp1 = (k - x)//y * Y + reg_score[j]
            else:
                tmp1 = ((k - x)//y - 1) * Y + reg_score[j]
            ans = max(ans, tmp0, tmp1)
        #print(i, j)
        #print(tmp0, tmp1)
        
        #if visit[j] == (k-x)%y + x:
        #    tmp = (k - x)//y * Y + reg_score[j]
        #    ans = max(ans, tmp)

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=[]
for i in range(N):
    trace=[-1 for _ in range(N)]
    cand=[0]
    trace[i]=0
    pos=i
    cnt=1
    cond=False
    while cnt<=K:
        pos=P[pos]-1
        if trace[pos]==-1:
            cand.append(cand[-1]+C[pos])
            trace[pos]=cnt
            cnt+=1
        else:
            cond=True
            init=trace[pos]
            loop=cnt-init
            point=cand[-1]+C[pos]-cand[init]
            break
    if cond:
        if K%loop>0:
            cand.append(cand[init]+(K-init)//loop*point+max(cand[init:init+(K-init)%loop+1])-cand[init])
        else:
            cand.append(cand[init]+(K-init)//loop*point)
    ans.append(max(cand[1:]))
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()))

# 移動可能回数が、全コマ数以下の場合
if K <= N:
    best = None
    for i in range(N):
        score = 0
        to = P[i] - 1
        for j in range(K):
            score += C[to]
            to = P[to] - 1
            if best == None or score > best:
                best = score
    print(best)
else:
    # 各移動回数におけるベストを記録しておく
    best = None
    bestMoveTime = None
    innerBests = [None] * N
    for i in range(N):
        score = 0
        to = P[i] - 1
        for j in range(N-1):
            score += C[to]
            to = P[to] - 1
            if best == None or score > best:
                best = score
                bestMoveTime = j+1
            if innerBests[j] == None or score > innerBests[j]:
                innerBests[j] = score

    aroundTimes = K // N
    sumC = sum(C)
 
    if K % N >= bestMoveTime:
        print(K%N)
        print(bestMoveTime)
        print(max(best, aroundTimes*sumC+best))
    else:
        print(max(best, (aroundTimes-1)*sumC+best+max(innerBests[:N-bestMoveTime+1]), aroundTimes*sumC+max(innerBests[:K%N])))

        # print(max(best, aroundTimes*sumC+max(innerBests[:K % N]),(aroundTimes-1)*sumC+best))
    








    # noAroundBest = None
    # noAroundBestTimes = None
    # for i in range(N):
    #     score = 0
    #     to = P[i] - 1
    #     for j in range(N-1):
    #         score += C[to]
    #         to = P[to] - 1
    #         if noAroundBest == None or score > noAroundBest:
    #             noAroundBest = score
    #             noAroundBestTimes = j+1

    # aroundTimes = K // N
    # times = K % N
    # best = None
    # for i in range(N):
    #     score = 0
    #     to = P[i] - 1
    #     for j in range(times):
    #         score += C[to]
    #         to = P[to] - 1
    #         if best == None or score > best:
    #             best = score
    # sumC = sum(C)
    # print(aroundTimes)
    # print(sumC)
    # print(aroundTimes*sumC+)
    # # print(noAroundBestTimes)
    # # print(noAroundBest)
    # # print(aroundTimes)
    # # print(sumC)
    # if noAroundBestTimes <= times:
    #     print(max(noAroundBest, sumC*aroundTimes+noAroundBestTimes))
    # else:
    #     print(max(noAroundBest, sumC*aroundTimes+best, sumC*(aroundTimes-1)+noAroundBestTimes))

Submission status: Wrong Answer

Solution code:
#hoge2
N, K = [int(_) for _ in input().split()]
P = [int(_) - 1 for _ in input().split()]
C = [int(_) for _ in input().split()]
child_parent = [0] * N
ans = -float('inf')
for p, c in enumerate(P):
    child_parent[c] = p
for i in range(N):
    f = i
    i_cnt = [None] * N
    i_cnt[i] = 0
    cnt_score = [0]
    score = 0
    cnt = 0
    loop = 0
    while True:
        cnt += 1
        if cnt > K:
            break
        i = P[i]
        score += C[i]
        if i_cnt[i] is not None:
            loop = 1
            break
        cnt_score += [score]
        i_cnt[i] = cnt
    if loop:
        cnt1 = i_cnt[i]
        score1 = cnt_score[cnt1]
        ans = max(ans, max(cnt_score[1:]))
        if score > score1:
            q, r = divmod((K - cnt1), cnt - cnt1)
            ans1 = (score - score1) * q + max([0] +
                                              cnt_score[cnt1:cnt1 + r + 1])
            ans = max(ans, ans1)
    else:
        ans = max([ans] + cnt_score[1:])
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] = P[i] - 1

used = [False] * N

ans = 0
for i in range(N):
    if not used[i]:
        arr = []
        j = i
        while True:
            arr.append(C[j])
            used[j] = True
            j = P[j]
            if i == j:
                break
            
        #print(arr)
        l = 0
        res = 0
        s = 0
        for j in range(len(arr)):
            s = max(s + arr[j], arr[j]);
            res = max(res, s);

        ans = max(ans, res)
        
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
n,k = ma()
Pt = lma()
P = [p-1 for p in Pt]
C = lma()
class unionfind():
    def __init__(self,n):
        self.par = list(range(n))
        self.size = [1]*n
        self.rank = [0]*n

    def root(self,x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]

    def same(self,x,y):
        return self.root(x) == self.root(y)

    def unite(self,x,y):
        x = self.root(x)
        y = self.root(y)
        if x==y:return
        else:
            if self.rank[x] < self.rank[y]:
                 x,y = y,x
            if self.rank[x] == self.rank[y]:
                self.rank[x]+=1
            self.par[y] = x
            self.size[x] +=self.size[y]
    def get_size(self,x):
        x = self.root(x)
        return self.size[x]
uf = unionfind(n)
for i in range(n):
    uf.unite(i,P[i])

def score(x):#xからスタートしたスコア
    l = uf.get_size(x)
    p,r = divmod(k,l)
    tmp = [-10**18-2 for i in range(l+1)]#一回の累積和
    tmp_p = [-10**18-2 for i in range(l+1)] #pサイクル目の累積和
    ret = 0
    if p==0:
        xt=x
        mx = -10*18-2
        for i in range(r):
            nex = P[xt]
            ret+=C[nex]
            xt = nex
            mx = max(mx,ret)
        return mx

    gain_cycle = 0
    xt=x
    for i in range(l):
        nex = P[xt]
        gain_cycle +=C[nex]
        ret+=C[nex]
        tmp[i+1] = ret
        if i<=r-1:
            tmp_p[i+1]=ret
        xt = nex
    if gain_cycle>0:
        return max(tmp_p) + p* gain_cycle
    else:
        return max(tmp)

        #print(ret,"ret")

ans = -10**18-2
for i in range(n):
    ans = max(ans,score(i))
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))

n,k=nii()
p=lnii()
c=lnii()

ans=-10**18
for i in range(1,n+1):
  x=i
  t_ans=[0]
  t_max=-10**18
  cnt=0
  while cnt<=n:
    next_x=p[x-1]
    t_max=max(t_max,t_ans[-1]+c[next_x-1])
    t_ans.append(t_ans[-1]+c[next_x-1])
    cnt+=1
    x=next_x

  ans=max(ans,t_max)

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):
    m=i
    co=0
    an=0
    for j in range(n):
        m=p[m]-1
        co+=1
        if m==i:
            break
    
        
        
         
    m=i
    x=[0 for j in range(co+1)]
    for j in range(co):
        m=p[m]-1
        x[j+1]=x[j]+c[m]
    
    an+=max(x[-1],0)*(k//co)
    if k%co!=0:      
        ans=max(ans,an+max(x[j] for j in range(1,(k%co)+1)))
    else:
        ans=max(ans,an+max(x[j] for j in range(1,co)))
        
    
print(ans)

Submission status: Wrong Answer

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

def max2(x,y):
    return x if x > y else y

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

off = max(C)
m2 = off
for i in range(N):
    tmp = 0
    m1 = off
    l = i
    S = 0
    k = 0
    for j in range(N):
        S += C[l]
        l = P[l] - 1
        if l==i:
            k = j+1
            break
    cnt = K // k - (K % k == 0)
    a = K%k + (K % k == 0)*k
    l = i
    d = []
    for j in range(a):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S > 0:
        m1 += cnt*S
    m2 = max2(m1, m2)

print(m2)
"""
4 10
2 3 4 1
1 2 3 4
"""

Submission status: Wrong Answer

Solution code:
import math


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    N, K = read_ints()
    P = [p-1 for p in read_ints()]
    C = read_ints()

    max_score = -math.inf
    for i in range(N):
        cycle_score = C[i]
        scores = [0, C[i]]
        j = P[i]
        k = K
        while k > 1 and i != j:
            cycle_score += C[j]
            scores.append(cycle_score)
            j = P[j]
            k -= 1
        cycle_size = len(scores)-1
        cycle_count = K//cycle_size
        max_score = max(max_score, max(scores[1:]))
        if cycle_count != 0:
            max_score = max(max_score, cycle_score*cycle_count+max(scores[:K%cycle_size+1]))
    return max_score


if __name__ == '__main__':
    print(solve())

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = list(map(int,input().split()))
used = [0]*n
c = list(map(int,input().split()))
ans = -float("INF")
def calc(x):
    l = []
    now = x
    score = 0
    while used[now] == 0:
        used[now] = 1
        l.append(c[now])
        now = p[now]-1
    S = sum(l)
    le = len(l)
    if S > 0 and k > le:
        score += (k//le-1)*S
        mod = k%le
        now = 0
        for i in range(le):
            cal = 0
            for j in range(le):
                if j == mod:
                    now = max(now,cal+S)
                cal += l[(i+j)%le]
                now = max(now,cal)
        return score+now
    else:
        mod = min(le,k)
        now = -float("INF")
        for i in range(le):
            cal = 0
            for j in range(mod):
                cal += l[(i+j)%le]
                now = max(now,cal)
        return score+now
    
for i in range(n):
    if used[i] == 0:
        ans = max(ans,calc(i))
print(ans)

Submission status: Wrong Answer

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

DP=[[C[P[n]]] for n in range(N)]

for start in range(N):
    visited=set()
    cur=P[start]
    while cur not in visited:
        visited.add(cur)
        cur = P[cur]
        DP[start].append(C[cur]+DP[start][-1])


for n in range(N):
    DP[n]=DP[n][:-1]

ans=-float("inf")
ans_start=None

for start in range(N):
    #pattern1(先に進んでからloopする)
    tmp_max=-float("inf")
    tmp_idx=None

    for i in range(min(K,len(DP[start]))):
        if tmp_max<DP[start][i]:
            tmp_max=DP[start][i]
            tmp_idx=i


    K_=K-tmp_idx-1
    if K_>=len(DP[start]) and DP[start][-1]>0:
        loop_cnt=K_//len(DP[start])
        tmp_max+=loop_cnt*DP[start][-1]
    if tmp_max>ans:
        ans=tmp_max
        ans_start=start

    #pattern2(loopしてから余を加算
    tmp_max=-float("inf")
    tmp_idx=None


    if DP[start][-1]>0:
        if K>=len(DP[start]) and DP[start][-1]>0:
           loop_cnt=K//len(DP[start])
           tmp_max+=loop_cnt*DP[start][-1]

        max_stop=0
        for i in range(K%len(DP[start])):
           if max_stop<DP[start][i]:
               max_stop=DP[start][i]
               stop=i
        tmp_max+=max_stop
        if tmp_max>ans:
           ans=tmp_max
           ans_start=start
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
P = list(map(int,input().split()))
P.insert(0,0)
C = list(map(int,input().split()))
C.insert(0,0)
A = []
hist = [0 for _ in range(N+1)]
for i in range(1,N+1):
    if hist[i]==0:
        a = [i]
        hist[i]=1
        j = i
        while True:
            if hist[P[j]]==0:
                a.append(P[j])
                hist[P[j]]=1
                j = P[j]
            else:break
        A.append(a)
B = []
for i in range(len(A)):
    a = A[i]
    n = len(a)
    b = []
    for j in range(n):
        b.append(C[a[j]])
    B.append(b)
S = {}
for i in range(len(B)):
    if i not in S:
        S[i] = {}
    n = len(B[i])
    a = B[i]+B[i]
    b = [0 for _ in range(2*n+1)]
    for j in range(1,2*n+1):
        b[j] = b[j-1]+a[j-1]
    for k in range(1,n+1):
        S[i][k]=-10**10
        for j in range(n-k+1):
            S[i][k] = max(S[i][k],b[j+k]-b[j])
ans = -10**10
for i in range(len(B)):
    n = len(B[i])
    a = B[i]+B[i]
    if K<=n:
        for k in range(1,K+1):
            ans = max(ans,S[i][k])
    else:
        if S[i][n]>0:
            cnt = (K//n-1)*S[i][n]
            cmax = -10**10
            b = [0 for _ in range(2*n+1)]
            for j in range(1,2*n+1):
                b[j] = b[j-1]+a[j-1]
            cnt1 = -10**10
            for k in range(1,n+K%n+1):
                for j in range(n+K%n+1-k+1):
                    cnt1 = max(cnt1,b[j+k]-b[j])
            cnt += cnt1
            ans = max(ans,cnt)
print(ans)

Submission status: Wrong Answer

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

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

ans = -10**18

for i in range(n):
    cyc, sco = cycle(i)

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int,input().split()))
c=list(map(int,input().split()))
ans=-10**9

for i in range(n):
    m=i
    co=0
    an=0
    for j in range(n):
        m=p[m]-1
        co+=1
        if m==i:
            break
    
        
        
         
    m=i
    x=[0 for j in range(co+1)]
    for j in range(co):
        m=p[m]-1
        x[j+1]=x[j]+c[m]
    
    an+=max(x[-1],0)*(k//co)
    if k%co!=0:
        
        ans=max(ans,an+max(x[j] for j in range(1,(k%co)+1)))
    else:ans=max(ans,an+max(x[j] for j in range(1,co)))
        
    
print(ans)

Submission status: Wrong Answer

Solution code:
import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict as dd

def maxSumSubSizek(arr, k): 
    n = len(arr)
    res = 0
    for i in range(k): 
        res += arr[i] 

    curr_sum = res 
    for i in range(k, n): 
        curr_sum += arr[i] - arr[i-k] 
        res = max(res, curr_sum) 
    return res 

def main():
    n,k = map(int, input().split())
    perm = [0] + list(map(int, input().split()))
    sqscore = [0] + list(map(int, input().split()))


    ans = -10**10
    visited = [0]*(n + 1)
    for i in range(1, n + 1):
        if not visited[i]:
            cycleScores = []
            j = i
            cycsum = 0
            maxsum = -10**10
            while not visited[j]:
                visited[j] = True
                score = sqscore[j]
                cycsum += score
                maxsum = max(maxsum, score)
                cycleScores.append(sqscore[j])
                j = perm[j]
            
            if maxsum <= 0:
                # All numbers are negative/0; take one step.
                ans = max(ans, maxsum)
            else:
                # positive numbers exist in cycle
                if k > len(cycleScores):
                    if cycsum <= 0:
                        msf = cycleScores[0]
                        for i in cycleScores[1:]:
                            msf = max(msf + i, i)
                            ans = max(ans, msf)
                    else:
                        # finish k/len(cycScores) cycles. Whatever is left, find subarray with max sum of that length
                        mult = k // len(cycleScores)

                        tempans = mult * cycsum
                        k -= mult * len(cycleScores)
                        
                        # find subarray of size k with in cycleScore with max Sum.
                        temp = cycleScores + cycleScores
                        for step in range(1, k + 1):
                            ans = max(ans, tempans + maxSumSubSizek(temp, step))
                else:
                    temp = cycleScores + cycleScores
                    for step in range(1, k + 1):
                        ans = max(ans, maxSumSubSizek(temp, step))
    print(ans)


        




































# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
 
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

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

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

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

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

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

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

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = [int(x)-1 for x in input().split()]
c = list(map(int, input().split()))
realans = -1001001001
for i in range(n):
    count = 0
    now = i
    score = 0
    for _ in range(n):
        if now == i and count != 0:
            break
        now = p[now]
        count += 1
        score += c[now]
    ans = 0
    ans += score * (k // count)
    nk = k % count
    if ans < 0:
        if nk == 0:
            nk = count+1
        ans = 0

    maxim = -1001001001
    now = i
    tmp = 0
    for j in range(nk):
        now = p[now]
        tmp += c[now]
        maxim = max(maxim, tmp)
    ans += maxim
    realans = max(realans, ans)
print(realans)

Submission status: Wrong Answer

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

if all([c <= 0 for c in C]):
    print(max(C))
    exit()

dp = [[[-1] * 2 for i in range(N)] for _ in range(35)]
for i, (p, c) in enumerate(zip(P, C)):
    dp[1][i][0] = p
    dp[1][i][1] = c

for i in range(1, 32):
    for j in range(N):
        dp[i+1][j][0] = dp[i][dp[i][j][0]][0]
        dp[i+1][j][1] = dp[i][dp[i][j][0]][1] + dp[i][j][1]


ans = 0
for i in range(N):
    tmp = 0
    for j in range(32):
        if j > 0:
            dp[j+1][i][1] = max(dp[j+1][i][1], dp[j][i][1])
        if K&(1<<j):
            tmp += dp[j+1][i][1]
        ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

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

x = [0] * n
t = list(range(1,n+1))

for j in range(min(k, 30000)):
    for i in range(n):
        x[i] += c[t[i]-1]
        t[i] = p[t[i]-1]
        ans = max(ans, x[i])

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(int, input().split()))
P = [p-1 for p in P]
C = list(map(int, input().split()))
D = {i:0 for i in range(N)}
L = []
i = 0
while i<N:
  if D[i]==1:
    i += 1
    continue
  else:
    D[i] = 1    
    box = [i]
    i = P[i]
  while box[0] != i:
    box.append(i)
    D[i] = 1
    i = P[i]
  L.append(box)
m = -10**18
for box in L:
    A = [C[i] for i in box]
    l = len(A)
    S = 0
    if sum(A)<=0:
        k = min(K, l)
    else: 
        S += sum(A)*((K-1)//l)
        k = ((K-1)%l)+1
    A *= 2
    M = -10**18
    for i in range(l):
        M_2 = [A[i]]
        for j in range(k):
            M_2.append(M_2[-1]+A[i+j+1])
        M = max(M, max(M_2))
    S += M
    m = max(S, m)
print(m)

Submission status: Wrong Answer

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

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