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


def _ia(): return map(int, sys.stdin.readline().strip().split())


def calc(arr, k):
    s = sum(arr)
    n = len(arr)
    kp = k % n if s > 0 else k
    l = min(kp, n)

    cm = max(arr) if s <= 0 else 0
    for i in range(n):
        cn = 0
        for ki in range(i, i+l):
            cn += arr[ki % n]
            cm = max(cn, cm)

    if s > 0:
        return s * (k//n) + cm
    else:
        return cm


def main():
    n, k = _ia()
    p = list(map(lambda x: x-1, _ia()))
    c = list(_ia())

    f = [False] * n
    g = []
    for idx in range(n):
        if f[idx]:
            continue

        nxt = idx
        tmp = [c[nxt]]
        f[nxt] = True

        for _ in range(n):
            nxt = p[nxt]
            if nxt == idx:
                break
            tmp.append(c[nxt])
            f[nxt] = True

        g.append(tmp)

    return max(calc(gi, k) for gi in g)


if __name__ == "__main__":
    print(main())

Submission status: Wrong Answer

Solution code:
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7


n,k=mdata()
p=mdata()
c=mdata()
l=[]
vis=[0]*n
ans=0
flag=0
for i in range(n):
    vis=[0]*n
    q=[i]
    c1=[c[i]]
    t=0
    while True:
        a=q[-1]
        vis[a]=1
        if vis[p[a]-1]==1:
            t=p[a]-1
            break
        else:
            q.append(p[a]-1)
            c1.append(c[p[a]-1])
    m=0
    m1=-c1[0]
    flag1 = 0
    for j in range(len(q)):
        if q[j]==t or j>k:
            break
        m1+=c1[j]
        if m1 >= 0:
            flag1 += 1
        m=max(m1,m)
    t1=m1
    if j<=k:
        for j1 in range(j,min(len(q),k)):
            m1 += c1[j1]
            m = max(m1, m)
            if m1>=0:
                flag1+=1
        s=sum(c1[j:])
        t1+=((k+1-j)//(len(q)-j))*s
        if t1 >= 0:
            flag1 += 1
        m1=0
        m2=0
        for j1 in range(j,j+(k+1-j)%(len(q)-j)):
            m1+=c1[j1]
            m2=max(m1,m2)
        t1+=m2
        if t1 >= 0:
            flag1 += 1
        m=max(m,t1)
    flag=max(flag,flag1)
    ans=max(ans,m)
if flag<2:
    ans=-INF
    for i in range(n):
        ans=max(ans,c[p[i]-1])
out(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**8)
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 li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
from itertools import accumulate #list(accumulate(A))

N, K = mi()
P = li()
C = li()
ans = -float('inf')

for i in range(N):
    ind = i
    his = []
    while True:
        ind = P[ind] - 1
        his.append(C[ind])
        if ind == i:
            his = list(accumulate(his))
            #print(his)
            L = len(his)
            if K > L:
                if his[-1] > 0:
                    if not K%L:
                        ans = max(ans, his[-1] * (K//L))
                    else:
                        ans = max(ans, max(his[:K%L]) + his[-1] * (K//L), his[-1] * (K//L), max(his))
                else:
                    ans = max(ans, max(his))
            else:
                ans = max(ans, max(his[:K]))
            break

print(ans)

Submission status: Wrong Answer

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

def calc(pos):
  X = [-1 for _ in range(N)]
  X2 = [-1 for _ in range(N)]
  k=0
  p=pos
  score=0
  ans=-1000000000
  X[p]=0
  X2[p]=0
  while k<K:
    p=P[p]
    score+=C[p]
    k+=1
    if X[p]!=-1:
      move_skip=max((K-k)//(k-X[p])-1,0)
      score+=(score-X2[p])*move_skip
      k+=move_skip*(k-X[p])
      
    X[p]=k
    X2[p]=score
    ans=max(score,ans)
  return ans
final_ans=-10000000


#for i in range(N):
#  final_ans=max(calc(i),final_ans)
final_ans=max(calc(0),final_ans)
print(final_ans)

Submission status: Wrong Answer

Solution code:

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

ans=0
check=set()

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

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

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

#周期の列を作りたい。
#[[1,2,4],[3,5]]のようなもの。
memo=[0 for i in range(N)]
shuuki=[]
#for i in range(N):
    

Graph=[]
for i in range(N):
    Graph.append([i+1,P[i]])
    Graph.append([P[i],i+1])


def find_root(root,x):
    y = root[x]
    if x == y:
        return x
    z = find_root(root,y)
    root[x] = z
    return z
 
def merge(root,size,x,y):
    x = find_root(root,x)
    y = find_root(root,y)
    if x == y:
        return
    sx,sy = size[x],size[y]
    if sx < sy:
        sx,sy = sy,sx
        x,y = y,x
    root[y] = x
    size[x] += sy
    
def UF_check(root,x,y):
    if find_root(root,x) == find_root(root,y):
        return True
    else:
        return False
    
def UF_make(graph,n):  #グラフと最大項を与えると、塊ごとにグルーピングする
    Root=list(range(n+1))
    Size=[1] * (n+1)
    for i in range(len(graph)):
        merge(Root,Size,graph[i][0],graph[i][1])
    for i in range(n+1):  #これを入れれば、UF_checkを使わずに一塊になる
        Root[i] = find_root(Root,i)
    Root.pop(0)  #
    return Root



UF=UF_make(Graph,N)
UF=[UF[i]-1 for i in range(N)]
P=[P[i]-1 for i in range(N)]
#print(UF)
#print(P)

shuuki=[[] for i in range(N+1)]
cnt=0
t=0
memo=[0 for i in range(N)]

while cnt<N:
    shuuki[UF[t]].append(t)
    cnt+=1
    memo[t]=1
    if memo[P[t]]==0:
        t=P[t]
    else:
        for i in range(N):
            if memo[i]==0:
                t=i
                break
    

#print(shuuki)
score=[]

for i in range(len(shuuki)):
    if shuuki[i]==[]:
        continue
    score.append([])
    for j in range(len(shuuki[i])):
        score[-1].append(C[shuuki[i][j]])
#print(score)
        
        
def maxscore(array,time):
    res=0
    if sum(array)>0 and time>=len(array):
        #最大限回せる
        res+=sum(array)*(time//len(array))
    time%=len(array)
    
    r=0
    array=array+array
    for i in range(len(array)):
        for j in range(time+1):
            if i+time<len(array):
                r=max(r,sum(array[i:i+time]))
    
    if max(array)<0:
        return max(array)
    else:
        return res+r


ans=-10**22
for i in range(len(score)):
    #print(score[i],maxscore(score[i],K))
    ans=max(ans,maxscore(score[i],K))

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()))
res = [0] * N
for i in range(N):
  x = i
  score = -float("inf")
  loopscore = 0
  loop = 0
  while x != i or loop == 0:
    loop += 1
    x = p[x] - 1
    loopscore += c[x]
    if loop <= K: score = max(score, loopscore)
  #print(loopscore)
  if loopscore <= 0:
    res[i] = score
  else:
    res[i] = K // loop * loopscore
    #print(res, loop, loopscore)
    plus = 0
    plusmx = 0
    x = i
    t = 0
    while t < K % loop:
      t += 1
      x = p[x] - 1
      plus += c[x]
      plusmx = max(plusmx, plus)
    res[i] += plusmx
  res[i] = max(res[i], score)

print(max(res))

Submission status: Wrong Answer

Solution code:
def main():
    n, k = map(int, input().split())
    p = list(map(int, input().split()))
    c = list(map(int, input().split()))
    max_cost = [0]*n
    ans = -10**10
    for i in range(n):
        s = i+1
        pi = p[i]
        cost = c[i]
        big = c[i]
        max_cost = [0]*n
        num = 1
        while pi != s:
            big = max(big, cost)
            max_cost[num] = big
            cost += c[pi-1]
            pi = p[pi-1]
            num += 1
        if cost <= 0:
            ans = max(ans, big)
        else:
            number = k//num
            if number:
                ans = max(ans, number*cost + max_cost[k%num])
            else:
                ans = max_cost[k-1]
    print(ans)
            

if __name__ == "__main__":
    main()

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=[]
checked=[False]*N
tmp=[0]
NEXT=P[0]-1
checked[0]=True
while False in checked:
    if checked[NEXT]:
        LOOP.append(tmp)
        tmp=[]
        NEXT=checked.index(False)
    else:
        tmp.append(NEXT)
        checked[NEXT]=True
        NEXT=P[NEXT]-1
LOOP.append(tmp)

ans=-float("inf")
for loop in LOOP:
    n=len(loop)
    score=[]
    for i in range(n):
        score.append(C[loop[i]])
    
    SUM=sum(score)
    score=score+score
    if SUM>0:
        m=K//n
        l=K-n*m
        tmp=SUM*m
        add=0
        for i in range(n):
            val=sum(score[i:i+l])
            add=max(add,val)
        tmp+=add
    else:
        tmp=-float("inf")
        for i in range(n):
            for j in range(1,min(n,K+1)):
                tmp=max(tmp,sum(score[i:i+j]))
    ans=max(ans,tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

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

ans = -float("inf")
for i in range(N):
    score_acc = [L[i]]
    cur = P[i] - 1
    while cur != i:
        score_acc.append(L[cur])
        cur = P[cur] - 1
    score_acc = list(accumulate(score_acc))
    M = len(score_acc)
    if M < K and score_acc[-1] > 0:
        res = K // M * score_acc[-1]
        if K % M:
            res += max(score_acc[: K % M])
        else:
            res += -score_acc[1] + max(score_acc)
        ans = max(ans, res)
    else:
        res = max(score_acc[:K])
        ans = max(ans, res)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))

# ループを見つける(5000), 一周のスコアを確認
is_visit = [0 for _ in range(n)]
loop = []

def search(i, j):
    if is_visit[i] == 0:
        is_visit[i] = j
        l.append(i)
        search(p[i]-1, j)
    else:
        pass

loop_id = 1
for i in range(n):
    l = []
    search(i, loop_id)
    if len(l) != 0:
        loop.append(l)
        loop_id += 1
# print(loop)
# print(is_visit)
s_list = [0 for _ in range(len(loop))]
for i in range(len(s_list)):
    l = loop[i]
    s = 0
    for j in range(len(l)):
        s += c[l[j]]
    s_list[i] = s

ans = [0 for _ in range(n)]
for i in range(n):
    # i からはじめて最大スコア
    l = loop[is_visit[i]-1] # 所属するループ
    tmp1 = 0 # ループによるスコア
    tmp_k = k
    s = s_list[is_visit[i]-1]
    if s > 0 and k > len(l):
        # 回るほどお得で一周より回れる
        tmp1 += s*(tmp_k//len(l))
        tmp_k -= (tmp_k//len(l))*len(l)
    else:
        tmp_k -= (tmp_k//len(l))*len(l)
        if tmp_k == 0:
            tmp_k = len(l)
    pointer = p[i]
    tmp2 = [c[pointer-1] for _ in range(tmp_k)] # 愚直に進んだ点数
    if tmp_k != 0:
        for j in range(1, tmp_k):
            # k回目までの累積和で最大を求める
            pointer = p[pointer-1]
            tmp2[j] = tmp2[j-1] + c[pointer-1]
    # print(i, l, s, tmp_k, tmp1, tmp2)
    if len(tmp2) != 0:
        ans[i] = tmp1 + max(tmp2)
    else:
        ans[i] = tmp1
# print(ans)
print(max(ans))

Submission status: Wrong Answer

Solution code:
import numpy as np

N, K = map(int, input().split())
P = np.array([int(s)-1 for s in input().split()])
C = np.array(list(map(int, input().split())))

res = np.max(C)
now = np.copy(C)
for _ in range(K-1):
    now += C[P]
    P = P[P]
    res = max(res,np.max(now))
print(res)

Submission status: Wrong Answer

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

loopcheck = [0]*N
As = []
for i in range(N):
    if loopcheck[i]==0:
        now = i
        A = []
        while loopcheck[now]==0:
            loopcheck[now]=1
            A.append(C[P[now]-1])
            now = P[now]-1
        As.append(A)
out = -1*10**10
for A in As:
    SA = sum(A)
    NA = len(A)
    B = A + A
    T = min(NA,K)
    outtmp = max(A)
    S = [0]
    kosu = 1
    for i in range(0,len(B)):
        S.append(S[-1]+B[i])
    for i in range(NA-1):
        for j in range(i+1,i+T+1):
            outtmp = max(outtmp,S[j]-S[i])
            if outtmp==S[j]-S[i]:
                kosu = j+1-i
    if SA>0:
        if kosu==NA:
            Y = K - (K//NA)*NA
            outtmpex = -10**10
            for i in range(NA-1):
                for j in range(i+1,i+Y+1):
                    outtmpex = max(outtmpex,S[j]-S[i])
            outtmp = SA*(K//NA)+outtmpex
        else:
            outtmp = outtmp+SA*((K-kosu)//NA)
    out = max(outtmp,out)
print(out)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 63


def run():
    N, K = map(int, sysread().split())
    P = list(map(int, sysread().split()))
    C = list(map(int, sysread().split()))
    P = [p-1 for p in P]

    loops = []
    checked = [0] * N
    loop = [0]
    for i in range(N):
        current = i
        while True:
            if not checked[current]:
                checked[current] = 1
                loop.append(C[current])
                current = P[current]
            else:
                if len(loop) == 1:break
                loops.append(loop)
                loop = [0]
                break
    loopSums = []
    for loop in loops:
        val = 0
        tmp = []
        for l in loop:
            val += l
            tmp.append(val)
        loopSums.append(tmp)
    #print(loops)
    #print(loopSums)
    ans = -INF
    for loop, loopSum in zip(loops, loopSums):
        for i in range(1, len(loop)):
            val = 0
            if loopSum[-1] < 0 or K <= len(loop)-1:
                j = i
                max_val = -INF
                iter = 0
                done = False
                while iter <= K:
                    if j >= len(loop):j=0
                    if i != j and j:
                        val += loop[j]
                        max_val = max(val, max_val)
                    j += 1
                    iter += 1
                    if done : break
                    if i == j: done = True
                ans = max(ans, max_val)
                continue


            rest = K
            #if K <= len(loop) - i - 1:
            #    val += loopSum[i + K - 1] - loopSum[i]
            #    ans = max(ans, val)
            #    continue
            rest -= len(loop) - i - 1
            val += loopSum[-1] - loopSum[i]
            val += (rest // (len(loop)-1)) * loopSum[-1]
            rest = rest % (len(loop) - 1)
            val += max(loopSum[:rest+1])
            ans = max(ans, val)

    print(ans)

if __name__ == "__main__":
    run()

Submission status: Wrong Answer

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

lis = []
for i in range(len(p)):
    ans = 0
    lislis = []
    masu = p[i]-1
    ans += c[masu]
    K = 1
    while True:
        lislis.append(ans)
        if K == k:
            break
        K += 1
        masu = p[p[i]-1]-1
        ans += c[masu]
    lis.append(max(lislis))

print(max(lis))

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])
    while(m<k and cur!=i):
        cur=arr[cur]
        co=cost[cur]
        l.append(l[-1]+co)
        m += 1
        ma=max(ma,l[-1])
    for j in range(k%m+1):
        ma = max(ma, l[-1] * (k//m) + l[j])
print(ma)

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

    return ans


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

Submission status: Wrong Answer

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
from sys import stdin
def main():
    readline = stdin.readline
    n,k = map(int,readline().split())
    P = list(map(int,readline().split()))
    C = list(map(int,readline().split()))
    dic = defaultdict(int)
    for i in range(n):
        dic[i+1] = P[i]
    ans = -float('inf')
    for start in range(n):
        nya = deque()
        root = defaultdict(int)
        pya = start+1
        cnt = 0
        SUM = 0
        while root[dic[pya]] == 0 and cnt < k:
            pya = dic[pya]
            nya.append(C[pya-1])
            cnt += 1
            SUM += C[pya-1]
            root[pya] = 1
            ans = max(ans,SUM)
        if cnt < k:
            need = k-cnt
            nl = len(nya)
            sumnya = sum(nya)
            a = need//nl
            nokori = need - nl*a
            for idx in range(nokori):
                SUM += nya[idx]
                ans = max(ans,SUM)
            SUM += sumnya * a
            ans = max(ans,SUM)
        else:
            ans = max(ans,SUM)
    print(ans)
main()

Submission status: Wrong Answer

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

cycles = []
seen = set()
for p in pp:
    i = p
    tmp = []
    while i not in seen:
        v = cc[i]
        tmp.append(v)
        seen.add(i)
        i = pp[i]
    if tmp:
        cycles.append(tmp)

ans = -float('inf')
for cycle in cycles:
    per_cycle = sum(cycle)
    m = len(cycle)
    if per_cycle > 0:
        cnt_cycle, resid = divmod(k, m)
    else:
        cnt_cycle = 0
        resid = min(k, m)

    if resid:
        dp = [cycle[:]]
        for k in range(1, resid):
            tmp = [0] * m
            for j in range(m):
                tmp[j] = dp[k-1][j] + cycle[(j + k)%m]
            dp.append(tmp)
        mx_resid = max(map(max, dp))
    else:
        mx_resid = 0
    ans_cycle = cnt_cycle * per_cycle + mx_resid
    ans = max(ans, ans_cycle)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
lst1 = [ int(i) for i in input().split()]
lst2 = [ int(i) for i in input().split()]
visited = [0]*n
count = 0
count_lst = []
x = 0
while True:
    count += lst2[x-1]
    visited[x-1] = 1
    if visited[x-1] != 0:
        for i, num in enumerate(visited):
            if num == 0:
                x = i
                count_lst.append(count)
                count = 0
        break
    else:
        x = lst1[x-1]
print(max(count_lst))

Submission status: Wrong Answer

Solution code:
import sys

def main():
    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()))
    seen = [0] * n
    accumulate = []
    for i in range(n):
        if seen[i] == 0:
            accumulate.append([c[i]])
            pre = i
            while True:
                if seen[pre] == 1:
                    accumulate[-1].pop()
                    break
                seen[pre] = 1
                now = p[pre]
                pre = now
                accumulate[-1].append(accumulate[-1][-1] + c[now])
    
    ans = -float("INF")
    for lst in accumulate:
        if len(lst) > k:
            for interval in range(1, k):
                for start in range(len(lst)):
                    if start + interval >= len(lst):
                        num = lst[-1] + lst[(start + interval) % len(lst)] - lst[start]                    
                    else:
                        num = lst[(start + interval)] - lst[start]
                    ans = max(ans, num)
        else:
            if lst[-1] > 0:
                for interval in range(1, k - len(lst) * (k // len(lst)) + 1):
                    for start in range(len(lst)):
                        num = (k // len(lst)) * lst[-1]
                        if start + interval >= len(lst):
                            num += (lst[-1] + lst[(start + interval) % len(lst)] - lst[start])
                        else:
                            num += lst[(start + interval)] - lst[start]
                        ans = max(ans, num)
            else:
                for interval in range(1, len(lst)):
                    for start in range(len(lst)):
                        if start + interval >= len(lst):
                            num = lst[-1] + lst[(start + interval) % len(lst)] - lst[start]                    
                        else:
                            num = lst[(start + interval)] - lst[start]
                        ans = max(ans, num)
            
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
(n, k), p, c = [[*map(int, i.split())] for i in open(0)]
visit = [0] * n
visit[0] = 1
loop = [0] * n
count = a = 0
while True:
    a = p[a] - 1
    if visit[a]:
        if loop[a]:
            break
        count += c[a]
        loop[a] = 1
    visit[a] = 1

ln = sum(loop)


def solve(x, t):
    ans = c[p[x] - 1]
    l = True
    sub = 0
    while True:
        if loop[x] and l:
            if count > 0:
                sub += t // ln * count
            t %= ln + t*(count<=0)
            l = False
        if t < 1:
            ans = max(sub, ans)
            return ans
        x = p[x] - 1
        sub += c[x]
        t -= 1
        ans = max(sub, ans)


print(max(solve(i, k) for i in range(n)))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# map(int, input().split())

def junkan_max_score(junkan, C, K):
    ruiseki = [0]
    for i in range(len(junkan)):
        j = junkan[i]
        ruiseki.append(ruiseki[-1]+C[j])

    n_junkan = int(K/len(junkan))
    if n_junkan == 0:
        return max(ruiseki[1:K+1])
    elif ruiseki[-1] <= 0:
        return max(ruiseki[1:])
    else:
        junkan_score = n_junkan*ruiseki[-1]
        nokori_K = K-(n_junkan*len(junkan))
        if nokori_K == 0:
            return junkan_score
        else:
            return junkan_score+max(ruiseki[1:nokori_K+1])
        

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

p_junkan = {i:[] for i in range(1,N+1)}

for i, lst in p_junkan.items():
    j = P[i-1]
    while j != i:
        lst.append(j-1)
        j = P[j-1]
    lst.append(i-1)

junkan_max = [junkan_max_score(lst, C, K) for i,lst in p_junkan.items()]
print(max(junkan_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()))

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

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

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = 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 = -5*(10**13)
for cc in CC:
    cca = list(accumulate(cc))
    sc = sum(cc)
    if sc < 0:
        # 1周分のうちの最大値
        if k < len(cc):
            ans = max(ans, max(cca[:k]))
        else:
            ans = max(ans, max(cca))
    else:
        # kk周したほうが良い
        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)