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:
#!/usr/bin/env python3
import sys


def solve(N: int, K: int, P: "List[int]", C: "List[int]"):

    if K > N-1:
        temp_max = C[0]
        for i in range(N):
            score_i = ["er"]*N 
            score_i_max = [0]*N
            h = P[i]-1
            score_i[0] = C[h]
            score_i_max[0] = C[h]
            if h == i: break
            for j in range(1, N):
                h = P[h]-1
                score_i[j] = score_i[j-1] + C[h]
                score_i_max[j] = max(score_i[j-1], score_i[j])
                if h == i: break

            # print(score_i)
            mod_k = K % (j+1)
            rat_k = K //(j+1)
            if score_i[j] > 0:
                t = rat_k * score_i[j] + max(0,(score_i_max[mod_k-1]))
                temp_max = max(t, temp_max)
            else:
                temp_max = max(score_i_max[j], temp_max)

        print(temp_max)
    
    elif K <= N:
        score = [[0]*N for i in range(N)]
        temp_max = C[0]
        for i in range(N):
            h = i
            for j in range(1, K):
                h = P[h]-1
                score[i][j] = score[i][j-1] + C[h]
                temp_max = max(score[i][j], temp_max)
        print(temp_max)


    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    C = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, K, P, C)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# D

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect
input = sys.stdin.readline

# 再起回数上限変更
# sys.setrecursionlimit(1000000)

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

d = [defaultdict(int) for _ in range(N)]
gdict = defaultdict(int)

ans = - float('inf')

for idx, p in enumerate(P):
    cnt = 1
    next = p
    if gdict[next] > 0:
        continue
    while True:
        if d[idx][next] > 0:
            break
        d[idx][next] = cnt
        gdict[next] = 1
        next = P[next]
        cnt += 1

for d_ in d:
    if len(d_) > 0:
        num = K % len(d_)
        l = [C[val] for val in list(d_.keys())]
        # print(d_, l)

        ans_temp = - float('inf')
        for i in range(len(l)):
            val = 0
            for k in range(num):
                val += l[(i+k) % len(l)]
                ans_temp = max(ans_temp, val)

        d_sum = sum(l)
        if d_sum > 0:
            num = K // len(d_)
            ans_temp += num * d_sum
            # print(ans_temp, K, len(d_), K // len(d_), num, d_sum, d_sum * num)

    ans = max(ans, ans_temp)

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)
    l = i
    for j in range(k-2):
        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:
N,K=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))

INF=10**15

vis=[0]*(N+1)

def find_cycle(start):
  vis[start]=1
  his=[start]
  now=start
  cost=[]
  while 1:
    new = P[now-1]
    cost.append(C[new-1])
    if vis[new]==1:
      return his,cost
    his.append(new)
    vis[new]=1
    now=new

cycles=[]
costs=[]
for i in range(N):
  if not vis[i+1]:
    his,cost=find_cycle(i+1)
    cycles.append(his)
    costs.append(cost)
    
def cumsum(array):
    new=[0]
    for i in range(len(array)):
        new.append(array[i]+new[-1])
    return new 
    
cumcost=[]
for i in range(len(costs)):
  cost=costs[i]
  cumcost.append(cumsum(cost*2))
  
def best_margin_cost(idx,r1):
  out=-INF
  for r2 in range(1,r1+1):
    for i in range(len(costs[idx])):
      tmp = cumcost[idx][i+r2]-cumcost[idx][i]
      out = max(tmp,out)
  return out
  
def opt_cost(idx):
  l = len(cycles[idx])
  SUM = sum(costs[idx])
  q,r=divmod(K,l)
  if K>=l:
    return max(SUM,0)*q+best_margin_cost(idx,l)
  else:
    return best_margin_cost(idx,K)

ans = -INF
for i in range(len(cycles)):
  ans = max(ans,opt_cost(i))
  
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**10
for i in range(n):
	K=k
	score=0
	pre_score=0
	visit=[0]*n
	now=i
	cnt=0
	while visit[now]==0:
		cnt+=1
		visit[now]=1
		now=p[now]-1
		pre_score+=c[now]
		if cnt!=1:
			score=max(score,pre_score)
		else:
			score=pre_score
		K-=1
		if K==0:
			break
	ans=max(score,ans)
	if K==0:
		continue
	loop=[0]
	NOW=now
	#NOWはループ元
	for j in range(n):
		now=p[now]-1
		loop.append(loop[-1]+c[now])
		if NOW==now:
			break
	pre_score2=pre_score
	pre_score3=pre_score
	KK=K#pre3用
	pre_score2+=max(loop[:min(K+1,len(loop))])
	score=max(score,pre_score2)
	pre_score+=max(loop[-1],0)*(K//(len(loop)-1))
	K%=(len(loop)-1)
	pre_score+=max(loop[:K+1])
	if KK>len(loop)-1:
		pre_score3+=max(loop[-1],0)*(K//(len(loop)-1)-1)
		pre_score3+=max(loop)
	score=max(score,pre_score,pre_score3)
	ans=max(ans,score)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(100000)


def main():
    n, k = [int(i) for i in input().strip().split()]
    P = [None] + [int(i) for i in input().strip().split()]
    C = [None] + [int(i) for i in input().strip().split()]
    seen = set()
    loops = []
    score = []
    _sums = []
    if max(C[1:]) < 0:
        ans = max(C[1:])
        print(ans)
        return
    # ループを探す
    for i in range(1, n + 1):
        flag = False
        loop = []
        sc = []
        _sum = 0
        j = i
        if j not in seen:
            flag = True
            while j not in loop:
                loop.append((j))
                sc.append(C[j])
                seen.add(j)
                _sum += C[j]
                j = P[j]
        if flag:
            loops.append(loop)
            _sums.append(_sum)
            score.append(sc)
    ans = -float("inf")
    # print(loops)
    # print(_sums)
    # print(score)
    if max(_sums) <= 0:
        for i in range(len(loops)):
            loop = loops[i]
            sc = score[i]
            for j in range(len(loop)):
                _tmp = 0
                for k in range(len(loop)):
                    ptr = (j + k) % len(loop)
                    _tmp += sc[ptr]
                    ans = max(ans, _tmp)
        print(ans)
        return
    # 各ループの評価をする
    for i in range(len(loops)):
        loop = loops[i]
        sc = score[i]
        _sum = _sums[i]
        tmp = _sum * (k // (len(loop)))
        rest = k % (len(loop))
        # print(loops)
        # print(tmp, rest)
        for j in range(len(loop)):
            _rs = 0
            # print("rest:", rest)
            for k in range(rest):
                ptr = (j + k) % len(loop)
                _rs += sc[ptr]
                ans = max(tmp + _rs, ans)
            # print("candidate", tmp, _rs)
    print(ans)
    return


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 + (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:
from itertools import accumulate

def main():
    inf=float("inf")
    n,k=map(int,input().split())
    plst=list(map(int,input().split()))
    clst=list(map(int,input().split()))
    sm=-inf

    seen=[0]*n
    for i in range(n):
        if seen[i] : continue
        pos=i
        work=[]
        while not seen[pos]:
            seen[pos]=1
            work.append(clst[pos])
            pos=plst[pos]-1
        nwork=len(work)
        work=[0]+list(accumulate(work))

        sm_add=0
        numcut=min(nwork,k)
        if work[-1]>0 and k>=nwork:
            sm_add=work[-1]*(k//nwork)
            numcut=k%nwork
        
        for i in range(nwork):
            for j in range(i,i+numcut+1):
                if j<nwork :
                    smwork=work[j+1]-work[i]
                else :
                    smwork=work[nwork]-work[i]+work[j-nwork]
                if smwork+sm_add>sm : sm=smwork+sm_add


    print(sm)

main()

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)
                n = (K - m) // t
                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:
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
            ans = max(ans, number*cost + max_cost[k%num])
    print(ans)
            

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

ans = -10**9
v = [False for _ in range(n)]
for i in range(n):
  j = i
  if v[j]:
    continue
  r = []
  while(v[j] == False):
    r.append(j)
    v[j] = True
    j = p[j]
  s = 0
  rr = []
  f1 = True
  f2 = True
  for ri in r:
    s += c[ri]
    rr.append(c[ri])
    if c[ri] > 0:
      f1 = False
    if c[ri] < 0:
      f2 = False
  if s >= 0:
  #if f2:
    k1 = k%len(r)
    k2 = k//len(r)
    rr = rr+rr
    now = 0
    for i in range(len(rr)-k1+1):
      now = max(sum(rr[i:i+k1]),now)
    now += s*k2
  else:
    if f1:
      now = -10**9
      for rri in rr:
        now = max(rri,now)
    else:
      rr = rr+rr
      a = 0
      b = 0
      now = -10**9
      while(b < len(rr)):
        if rr[a] <= 0:
          a += 1
          b += 1
        else:
          #print('a,b:',a,b)
          now = max(sum(rr[a:b+1]),now)
          b += 1
          if b-a >= k:
            a += 1
  #print(now,r)
  ans = max(ans,now)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
r = []
visit = [0] * n
for i in range(n):
    if not visit[i]:
        x = []
        j = i
        while True:
            if visit[j]:
                break
            x.append(c[j])
            visit[j] = 1
            j = p[j] - 1
        r.append(x)
l = len(r)
ans = -1145141919810
for x in r:
    ll = len(x)
    y = [0] * (ll + 1)
    for i in range(ll):
        y[i + 1] = y[i] + x[i]
    sumx = y[ll]
    a = 0
    b = -1145141919810
    kk = k
    #print(kk, ll)
    if ll < kk:
        if sumx > 0:
            a = (kk // ll) * sumx
        kk -= ll * (kk // ll)
        b = 0
    #print(a, kk, ll, sumx)
    #print(y)
    for i in range(1, kk + 1):
        for j in range(ll + 1 - i):
            #print(i + j, j)
            b = max(y[i + j] - y[j], b)
    for i in range(kk - 1):
        for j in range(i + 1):
            #print(ll - 1 - (j - 1), 1 + (i - j))
            b = max(y[ll] - (y[ll - 2 - (j - 1)] - y[1 + (i - j)]), b)
    ans = max(a + b, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [0] + list(map(int, input().split()))
C = list(map(int, input().split()))
ans = max(C)
C = [0] + C

roop, fact = [], set()
for i in range(1, N+1):
    if i in fact:
        continue
    else:
        s = i
        fact.add(s)
        root = [s]
        while P[s] not in fact:
            s = P[s]
            root.append(s)
            fact.add(s)
        roop.append(root)

for x in range(len(roop)):
    length = len(roop[x])
    roop_score = [[C[roop[x][i]] for i in range(length)]]
    print(roop_score[0])
    per_roop = 0

    if length <= K:
        per_roop = sum(roop_score[0])
        ans = max(ans, K//length * per_roop)
    if length < K:
        ans = max(ans, max(roop_score[0]) + (K - 1)//length * per_roop)

    for i in range(1, min(length-1, K)):
        roop_score.append([])
        for j in range(length):
            roop_score[i].append(roop_score[0][j-1] + roop_score[i-1][j])
        ans = max(ans, max(roop_score[i]) + (K - (i+1))//length * max(0, per_roop))

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
listP = list(map(int, input().split()))
listC = list(map(int, input().split()))

maxP = ""
for p in listP:
    pointMemori = []
    maxS = ""
    sm = 0
    count = 0
    start = p
    i = p
    while count <= k:
        count+=1
        sm+=listC[i-1]
        pointMemori.append(sm)
        if maxS == "" or maxS < sm:
            maxS = sm
        i = listP[i-1]
        if i == start:
            break
    if i == start and sm > 0:
        sho = k//count
        amari = k%count
        
        if amari >= 1:
            maxS = max(
                maxS, sho*sm+max(pointMemori[:amari]), sho*(sm-1)+max(pointMemori[:amari]))
        else:
            maxS = max(maxS, sho*sm, sho*(sm-1)+maxS)
    if maxP == "" or maxP < maxS:
        maxP = maxS
print(maxP)

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.insert(0, 0)
C.insert(0, 0)

ans = -float("inf")
for i in range(1, N+1):
    S = i
    visited = [False for i in range(N+1)]
    point = []
    while visited[S] == False:
        point.append(C[S])
        visited[S] = True
        S = P[S]
    
    L = len(point)
    index = -1
    for i in range(L):
        if point[i] == C[S]:
            index = i
            break

    not_loop = index
    loop = L-index
    Loop = point[index:]
    B = 0
    for i in range(index, L):
        B += point[i]
    if B >= 0:
        if not_loop > K:
            D = 0
            for i in range(K):
                D += point[i]
                ans = max(D, ans)
        if not_loop <= K:
            D = 0
            for i in range(not_loop):
                D += point[i]
            K -= not_loop
            for i in range(1, loop):
                Loop[i] += Loop[i-1]
            if K % loop == 0:
                ans = max(ans, D+B*(K//loop-1)+Loop[-1], D+B*(K//loop))
            elif K % loop != 0:
                ans = max(ans, D+B*(K//loop-1) +
                          Loop[-1], D+B*(K//loop)+Loop[K % loop-1])

    else:
        ans = max(point[0],ans)
        for i in range(1, min(L, K)):
            point[i] += point[i-1]
            ans = max(point[i], ans)


print(ans)

Submission status: Wrong Answer

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

P = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]

unvisited = set(range(N))
cycles = []
while unvisited:
    cycles.append([])
    start = unvisited.pop()
    cycles[-1].append(C[start])
    temp = P[start]-1
    while temp in unvisited:
        unvisited.remove(temp)
        cycles[-1].append(C[temp])
        temp = P[temp]-1

maxsum = -10 ** 9
for cycle in cycles:
    doublecycle = cycle*2
    Kdiv = (K-1) // len(cycle)
    Krem = (K-1) % len(cycle) + 1
    for i in range(Krem):
        for j in range(len(cycle)):
            maxsum = max(maxsum,sum(doublecycle[j:j+i+1]))
    cyclesum = sum(cycle)
    if cyclesum > 0:
        maxsum = cyclesum * Kdiv + maxsum

print(maxsum)

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]
        # print(tmp,P[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)

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

        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)
            # print(M,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)
                # print(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 > M:
                            break
                        res = max(res,accumT[j]-accumT[i])
                ans = max(ans,res)
                # print(M,res)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

max_score = -10**11
for i in range(N):
  score = 0
  count = 0
  index = []
  j = i
  n = 0
  for _ in range(N):
    j = P[j]-1
    index.append(i)
    count += C[j]
    n += 1
    if j == i:
      break
  k = K%n
  score = (K//n)*count
  if score < 0:
    score = 0
    if k == 0:
      k = 1
  max_v = -10**9
  v = 0
  for _ in range(k):
    j = P[j]-1
    v += C[j]
    max_v = max(max_v, v)
  max_score = max(max_score, score+max_v)

print(max_score)

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
        max_score = max(max_score, max(scores[1:]))
        if k > 1:
            cycle_size = len(scores)-1
            cycle_count = K//cycle_size
            max_score = max(max_score, max(scores[1:]), 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  = [0] + list(map(int,input().split()))
C = [0] + list(map(int,input().split()))

L = [[] for i in range(n+1)]
length = [0]*(n+1)

for i in range(1,n+1):
    x = i

    s = set([])
    sw = 0
    for j in range(1,n+1):

        x = P[x]
        if P[x] in s and sw == 0:
            length[i] = j-1
            sw = 1
            
        s.add(P[x])
        point = C[x]
        if j != 1:
            L[i].append(L[i][-1]+C[x])
        else:
            L[i].append(C[x])
            
    if sw == 0:
        length[i] = n


ans = - float("Inf")

if k > n:

    
    for i in range(1,n+1):
        m = k//length[i]
        p = k%length[i]
        if p == 0:
             point = m * L[i][length[i]-1]
        else:
            point = m * L[i][length[i]-1] + max(L[i][:p])

        ans = max(ans, point)

    
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), ans)
        
else:
    for a in L[1:]:
        if a != []:
            ans = max(max(a[:k]), ans)
        
print(ans)

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

visited = {}
loops = {}

for i in range(n):
    cur = i
    loop = [c[i]]

    if i in visited:
        continue
    else:
        visited[i] = [i, 0]

    for j in range(n):
        nexts = p[cur]-1
        if nexts in visited:
            break

        loop.append(c[nexts])
        visited[nexts] = [i, j+1]

        cur = nexts
        if cur == i:
            break

    loops[i] = loop

ans = -10000000000
for i in range(n):
    loop = loops[visited[i][0]]
    turns = k%len(loop)
    if k == len(loop):
        turns = k

    maxloop = -10000000000
    cnt = 0
    j = visited[i][1]
    for _ in range(turns):
        cnt += loop[j]
        if cnt > maxloop:
            maxloop = cnt

        j += 1
        if j == len(loop):
            j = 0

    nloops = k//len(loop)
    if nloops > 0:
        loopsum = sum(loop)
        if loopsum > 0:
            maxloop += nloops*loopsum

    if maxloop > ans:
        ans = maxloop

print(ans)

Submission status: Wrong Answer

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

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

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

ans = 0
used = [False]*n

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

        cs = [c[i] for i in gr]
        s = sum(cs)
        point = 0
        r = k
        if k > len(gr):
            if s > 0:
                point += s*(k//len(gr))
                r -= len(gr)*(k//len(gr))
            else:
                r = len(gr)
        
        cs = cs + cs
        plus = 0
        for i in range(len(gr)):
            nowSum = 0
            for g in range(r):
                nowSum += cs[i+g]
                plus = max(plus, nowSum)
        
        point += plus
        ans = max(ans, point)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from itertools import accumulate
import sys
sys.setrecursionlimit(1000000)

def func(x):
    return x - 1

def main():
    N, K = map(int, input().split())
    P = list(map(func,map(int, input().split())))
    C = list(map(int, input().split()))
    flag = False
    for i in range(N):
        if C[i] >= 0:
            flag = True
    if not flag:
        print(max(C))
        exit()
    cand = []
    visited = [False] * N
    for i in range(N):
        if not visited[i]:
            Q = deque([i])
            tmp = []
            while Q:
                x = Q.pop()
                visited[x] = True
                v = P[x]
                if not visited[v]:
                    Q.append(v)
                    tmp.append(C[v])
            tmp.append(C[v])
            cand.append(tmp+tmp)
    ans = 0
    for item in cand:
        tmp_score = 0
        S = sum(item) // 2
        L = len(item) // 2
        D = [0] + list(accumulate(item))
        if K <= L:
            cnt = K
            for l in range(L):
                for j in range(cnt):
                    tmp = D[l+j+1] - D[l] 
                    tmp_score = max(tmp_score, tmp)
            ans = max(ans, tmp_score)
        else:
            if S > 0:
                cnt = K % L
                for l in range(L):
                    for j in range(cnt):
                        tmp = D[l+j+1] - D[l]
                        tmp_score = max(tmp_score, tmp)
                tmp_score += (K // L) * S
                ans = max(ans, tmp_score)
            else:
                cnt = min(K,L)
                for l in range(L):
                    for j in range(cnt):
                        tmp = D[l+j+1] - D[l] 
                        tmp_score = max(tmp_score, tmp)
                ans = max(ans, tmp_score)

    print(ans)
            




if __name__ == "__main__":
    main()

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 = score1 + (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:
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]
    print(ans)
            

if __name__ == "__main__":
    main()