Problem:


Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



Sample input:
5 2
2 4 5 1 3
3 4 -10 -8 8


Sample output:
8

Submission status: Wrong Answer

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

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

INF = float('inf')

max_points = []
for i in range(N):
    max_point = -INF
    visit = [0] * N
    visit[i] = 1
    S = [0]
    pos = P[i]
    loop = 0  # P は順列なので、すでにvisitした点に戻ったとき、loopが位数となる
    while True:
        if visit[pos] == 0:
            visit[pos] = 1
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
        else:
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
            break

    loop_point = S[loop]
    # print(loop_point)
    # print(i, visit)
    if loop > K:
        max_point = max(S[1:])
    else:
        if loop_point > 0:
            loop_num = K // loop
            max_point = max(max_point, loop_point * loop_num + max(S[:(K%loop)+1]))
            max_point = max(max_point, loop_point * (loop_num-1) + max(S[1:loop]))
        else:
            max_point = max(S[1:loop])

    max_points.append(max_point)

print(max(max_points))

Submission status: Wrong Answer

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

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

INF = float('inf')

max_points = []
for i in range(N):
    max_point = -INF
    visit = [0] * N
    visit[i] = 1
    S = [0]
    pos = P[i]
    loop = 0  # P は順列なので、すでにvisitした点に戻ったとき、loopが位数となる
    while True:
        if visit[pos] == 0:
            visit[pos] = 1
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
        else:
            S.append(S[loop] + C[pos])
            pos = P[pos]
            loop += 1
            break

    loop_point = S[loop]
    # print(loop_point)
    # print(i, visit)
    if loop > K:
        max_point = max(S[1:])
    else:
        if loop_point > 0:
            loop_num = K // loop
            max_point = max(max_point, loop_point * loop_num + max(S[:(K%loop)+1]))
            max_point = max(max_point, loop_point * (loop_num-1) + max(S[1:loop]))
        else:
            max_point = max(S[1:loop])

    max_points.append(max_point)

print(max(max_points))

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict, deque
from copy import deepcopy
    
input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]
def end_of_loop():raise StopIteration

def main():
    N, K = MI()
    P = LI()
    C = LI()
    #1週下再に加算されるスコア並びにあるますから出発した際に１マス進んだ際のスコアがわかればよい。
    #初期化
    score = sum(C)
    result = max(C)
    d = [-float('inf')] * N
    #開始点
    for i in range(N):
        result = - float('inf')
        result2= 0
        # start
        temp = i
        for j in range(N):
            temp = P[temp]-1
            result2+=C[temp]
            d[j] = max(result2, d[j])

    if K > N:
        ans = K // N
        hosei = ans * score
        amari = K % N
        if amari != 0:
            print(max(max(d), max(d[0:amari])+hosei, max(d)+hosei-score))
        else:
            print(max(max(d), hosei))
    else:
        print(max(d[0:K]))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

n, k = list(map(int, input().split()))
p = list(map(lambda x: int(x) - 1, input().split()))
c = list(map(int, input().split()))

best = max(c)
for i in range(n):
    curr = 0
    score = [0]
    start = i
    while p[start] != i:
        start = p[start]
        curr += c[start]
        score.append(curr)
    cycle_score = score[-1] + c[i]
    cycle_len = len(score)

    for j in range(cycle_len):
        # if j <= k and j != 0:
        if j <= k:
            cycles = (k-j)//cycle_len
            thing = score[j] + max(0, cycle_score) * cycles
            best = max(best, thing)
        # elif j == 0 and k >= cycle_len:
        #     thing = cycle_score * k//cycle_len
        #     best = max(best, thing)
print(best)

Submission status: Wrong Answer

Solution code:

import collections

n, k = map(int, input().split())

p = list(map(int, input().split()))
c = list(map(int, input().split()))


def maxv(arr, k):

    n = len(arr)
    sumA = arr[:] + [0]

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

    deque = collections.deque()

    ans = -float('inf')

    for i in range(-1, n):

        while deque and i - deque[0] > k:
            deque.popleft()

        if deque:
            ans = max(ans, sumA[i] - sumA[deque[0]])

        while deque and sumA[ deque[-1] ] > sumA[i]:
            deque.pop()

        deque.append(i)

    return ans



def sol(n, k, p, c):

    vs = set()

    p = [0] + p
    c = [0] + c

    ans = -float('inf')

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

        if i not in vs:
            
            u = i
            vs.add(u)
            temp = [ c[p[u]] ]
            
            while p[u] not in vs:

                u = p[u]
                vs.add(u)
                temp.append( c[p[u]] )

            sum_temp = sum(temp)
            n_temp = len(temp)

            if sum_temp <= 0:

                total = maxv(temp + temp, min(n_temp, k))

                ans = max(ans, total)

                continue


            temp_k = k % n_temp

            if temp_k == 0:
                temp_k = n_temp
                k -= n_temp

            num_k = k // n_temp

            

            total = maxv( temp + temp, temp_k ) + max(sum_temp, 0) * (num_k)

            ans = max(ans, total)


            # print (temp, ans, '|', temp + temp, temp_k, maxv( temp + temp, temp_k ))

    if ans < 0:
        ans = max(c[1:])

    return ans


ans = sol(n, k, p, c)    

print (ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

n, k = list(map(int, input().split()))
p = list(map(lambda x: int(x) - 1, input().split()))
c = list(map(int, input().split()))

best = max(c)
for i in range(n):
    curr = 0
    score = [0]
    start = i
    while p[start] != i:
        start = p[start]
        curr += c[start]
        score.append(curr)
    cycle_score = score[-1] + c[i]
    cycle_len = len(score)

    for j in range(cycle_len):
        if j <= k and j != 0:
            cycles = (k-j)//cycle_len
            thing = score[j] + max(0, cycle_score) * cycles
            best = max(best, thing)
        # elif j == 0 and k >= cycle_len:
        #     thing = cycle_score * k//cycle_len
        #     best = max(best, thing)
print(best)

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()))
ls = [0]*n
z = 0
l = 0
lv = 0

for i in range(n):
    v = 0
    tmp = i
    cl = [0]*n
    for j in range(n):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if ls[j] < v or ls[j]==0:
                ls[j] = v
            if cl[tmp] != 0:
                if lv < v - c[tmp]:
                    l = n - cl.count(0)
                    lv = v - c[tmp]
                break
            cl[tmp] += 1

if k >= n and l > 0:
    z = lv * int(k/l)
    k = k%l
elif k >= n and l == 0:
    z = sum(c) * int(k/n)
    k = k%n

#print(z,ls)

if z > 0 and k != 0:
    print(z+max(ls[:k]))
elif z < 0 and k != 0:
    print(max(ls[:k]))
else:
    print(max(ls))

Submission status: Wrong Answer

Solution code:
import sys

class UnionFind():
  def __init__(self, n):
    self.n = n
    self.parents = [-1] * n

  def find(self, x):
    if self.parents[x] < 0:
      return x
    else:
      self.parents[x] = self.find(self.parents[x])
      return self.parents[x]

  def union(self, x, y):
    x = self.find(x)
    y = self.find(y)

    if x == y:
      return

    if self.parents[x] > self.parents[y]:
      x, y = y, x

    self.parents[x] += self.parents[y]
    self.parents[y] = x

  def size(self, x):
    return -self.parents[self.find(x)]

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

  def members(self, x):
    root = self.find(x)
    return [i for i in range(self.n) if self.find(i) == root]

  def roots(self):
    return [i for i, x in enumerate(self.parents) if x < 0]

  def group_count(self):
    return len(self.roots())

  def all_group_members(self):
    return {r: self.members(r) for r in self.roots()}

  def __str__(self):
    return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N, K = map(int, input().split())

Ps = [0]+list(map(int, input().split()))
Cs = [0]+list(map(int, input().split()))

uf = UnionFind(N+1)
dic = {}

rlt = -sys.maxsize
for i in range(1,N+1):
  uf.union(i,Ps[i])
  
for i in range(1,N+1):
  j = uf.find(i) 
  if j in dic:
    dic[j] += Cs[Ps[i]]
  else:
    dic[j] = Cs[Ps[i]]
    
rlt = -sys.maxsize

for i in range(1,N+1):
  k = uf.find(i)
  cnt = K//uf.size(i)
  md = K % uf.size(i)
  tmp = 0
  if dic[k] > 0:
    tmp = cnt*dic[k]
  tmp2 = Cs[Ps[i]]
  tmp3 = 0
  j = i
  for _ in range(1,md+1):
    j = Ps[j]
    tmp3 += Cs[j]
    tmp2 = max(tmp2, tmp3)
  if (tmp2 >= 0 and md > 0) or dic[k] < 0 or cnt == 0:
    tmp += tmp2
  rlt = max(tmp, rlt)
  
print(rlt)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pn = list(map(int, input().split()))
cn = list(map(int, input().split()))

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        if now == start:
            rp = j
            break
    else:
        continue
    if total <= 0:
        continue
    else:
        if k%rp==0:
            ans = max(ans, total * (k//rp))
        else:
            s = k%rp
            now = start
            total2 = 0
            ans1 =0
            for _ in range(1, s + 1):
                now = pn[now] - 1
                total2 += cn[now]
                ans1 = max(ans1, total2)
            ans2 = ans1 + total * (k//rp)
            ans = max(ans, ans2)
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()]

maxsum = -10 ** 9

for i in range(N):
    cycle = []
    cycle.append(C[i])
    temp = P[i]-1
    while temp != i:
        cycle.append(C[temp])
        temp = P[temp]-1

    Kdiv = (K-1) // len(cycle)
    Krem = (K-1) % len(cycle) + 1

    cyclesum = sum(cycle)
    for j in range(Krem):
        psum = sum(cycle[:j+1])
        if cyclesum > 0:
            psum += cyclesum * Kdiv
        maxsum = max(maxsum, psum)

print(maxsum)

Submission status: Wrong Answer

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

F=[0]*N
I=[0]*N
CN=[0]*N

for i in range(N):
  around=0
  cnt=0
  A=[]
  if F[i]==0:
    F[i]=1
    around+=1
    cnt+=C[i]
    nex=P[i]-1
    A.append(i)
    while F[nex]==0:
      A.append(nex)
      F[nex]=1
      around+=1
      cnt+=C[nex]
      nex=P[nex]-1
    for j in A:
      I[j]=around
      CN[j]=cnt
#print(F)
#print(I)
#print(CN)
ans=-(10**9)*2
for i in range(N):
  cnt=C[i]
  
  #動かす回数が一周に満たない時
  if K+1<I[i]:
    d=0
    nex=i
    for j in range(K+1):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  #動かす回数が一周を超えるとき
  elif CN[i]<0:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  else:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
    acnt=cnt
    bcnt=C[i]
    syuukai=(K+1)//I[i]
    nokori=(K+1)%I[i]
    syuukai-=1
    nokori+=I[i]
    d=0
    nex=i
    for j in range(nokori-1):
      d+=C[nex]
      nex=P[nex]-1
      bcnt=max(d,bcnt)
    bcnt+=syuukai*CN[i]
    cnt=max(acnt,bcnt)
  ans=max(ans,cnt)
print(max(ans,max(C)))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pn = list(map(int, input().split()))
cn = list(map(int, input().split()))

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        if now == start:
            rp = k
            break
    else:
        continue
    if total <= 0:
        continue
    else:
        if k%rp==0:
            ans = max(ans, total * (k//rp))
        else:
            s = k%rp
            now = start
            total2 = 0
            ans1 =0
            for _ in range(1, s + 1):
                now = pn[now] - 1
                total2 += cn[now]
                ans1 = max(ans1, total2)
            ans2 = ans1 + total * (k//rp)
            ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

Solution code:

import collections

n, k = map(int, input().split())

p = list(map(int, input().split()))
c = list(map(int, input().split()))


def maxv(arr, k):

    n = len(arr)
    sumA = arr[:] + [0]

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

    deque = collections.deque()

    ans = -float('inf')

    for i in range(-1, n):

        while deque and i - deque[0] > k:
            deque.popleft()

        if deque:
            ans = max(ans, sumA[i] - sumA[deque[0]])

        while deque and sumA[ deque[-1] ] > sumA[i]:
            deque.pop()

        deque.append(i)

    return ans



def sol(n, k, p, c):

    vs = set()

    p = [0] + p
    c = [0] + c

    ans = -float('inf')

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

        if i not in vs:
            
            u = i
            vs.add(u)
            temp = [ c[p[u]] ]
            
            while p[u] not in vs:

                u = p[u]
                vs.add(u)
                temp.append( c[p[u]] )

            sum_temp = sum(temp)
            n_temp = len(temp)


            temp_k = k % n_temp

            if temp_k == 0:
                temp_k = n_temp
                k -= n_temp

            num_k = k // n_temp

            # if num_k >= 1:
            #     num_k -= 1
            #     temp_k = k % n_temp + n_temp
            # else:
            #     temp_k = k % n_temp

            # if num_k == 1:
            #     num_k = 0
            #     temp_k = k
            # else:
                




            total = maxv( temp + temp, temp_k ) + max(sum_temp, 0) * (num_k)

            ans = max(ans, total)


            # print (temp, ans, '|', temp + temp, temp_k, maxv( temp + temp, temp_k ))

    if ans < 0:
        ans = max(c[1:])

    return ans


ans = sol(n, k, p, c)    

print (ans)

Submission status: Wrong Answer

Solution code:
[n, k] = map(int, input().split())
strp = input().split()
strc = input().split()
p = [0]
c = [0]
for i in range(n):
	p.append(int(strp[i]))
	c.append(int(strc[i]))

# p[1].append(123)
# print(p)
# print(c)
chain = [[i] for i in range(n+1)]
score = [[c[i]] for i in range(n+1)]

# set chain and score
for i in range(1,n+1):
	next = p[i]
	while(i != next):
		chain[i].append(next)
		score[i].append(score[i][-1] + c[next])
		next = p[next]

bests = [0]
for i in range(1,n+1):
	l = len(chain[i])
	lastlen = k%l
	if score[i][-1] <= 0:
		tmp = c[i]
		if k%l == 0:
			lastlen = l
		for j in range(lastlen):
			if score[i][j] > tmp:
				tmp = score[i][j]
		best = tmp
	else:
		div = int(k/l)
		if k%l == 0:
			lastlen = l
			div -= 1
		best = div*score[i][-1]
		tmp = c[i]
		for j in range(k%l):
			if score[i][j] > tmp:
				tmp = score[i][j]
		best += tmp
		# best += max(score[i][:k%l])
	bests.append(best)
# print(bests[])
print(max(bests[1:]))
# print(p)
# print(c)
# print(chain)
# print(score)

Submission status: Wrong Answer

Solution code:
N,K = (int(T) for T in input().split())
Next = [int(T)-1 for T in input().split()]
GetP = [int(T) for T in input().split()]
Disp = [0]*N
for TN in range(0,N):
    NowP = TN
    Point = [0]*(N+1)
    RoopC = 0
    RoopFlag = False
    for TK in range(0,K):
        RoopC += 1
        NowP = Next[NowP]
        Point[RoopC] = Point[RoopC-1]+GetP[NowP]
        if NowP==TN:
            RoopFlag = True
            Point = Point[:(RoopC+1)]
            break

    if RoopFlag:
        RoopP = Point[-1]
        if RoopP<=0:
            Disp[TN] = max(Point[1:])
        else:
            Rest = K-RoopC*(K//RoopC)
            Disp[TN] = max(RoopP*(K//RoopC)+max(Point[:Rest+1]),RoopP*((K//RoopC)-1)+max(Point[1:]))           
    else:
        Disp[TN] = max(Point[1:])
print(max(Disp))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pn = list(map(int, input().split()))
cn = list(map(int, input().split()))

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        if now == start:
            rp = k
            break
    else:
        continue
    if total <= 0:
        continue
    else:
        if k%j==0:
            ans = max(ans, total * (k//j))
        else:
            s = k%j
            now = start
            total2 = 0
            ans1 =0
            for _ in range(1, s + 1):
                now = pn[now] - 1
                total2 += cn[now]
                ans1 = max(ans1, total2)
            ans2 = ans1 + total * (k//j)
            ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

Solution code:

import collections

n, k = map(int, input().split())

p = list(map(int, input().split()))
c = list(map(int, input().split()))


def maxv(arr, k):

    n = len(arr)
    sumA = arr[:] + [0]

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

    deque = collections.deque()

    ans = -float('inf')

    for i in range(-1, n):

        while deque and i - deque[0] > k:
            deque.popleft()

        if deque:
            ans = max(ans, sumA[i] - sumA[deque[0]])

        while deque and sumA[ deque[-1] ] > sumA[i]:
            deque.pop()

        deque.append(i)

    return ans



def sol(n, k, p, c):

    vs = set()

    p = [0] + p
    c = [0] + c

    ans = -float('inf')

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

        if i not in vs:
            
            u = i
            vs.add(u)
            temp = [ c[p[u]] ]
            
            while p[u] not in vs:

                u = p[u]
                vs.add(u)
                temp.append( c[p[u]] )

            sum_temp = sum(temp)
            n_temp = len(temp)

            num_k = k // n_temp

            # if num_k >= 1:
            #     num_k -= 1
            #     temp_k = k % n_temp + n_temp
            # else:
            #     temp_k = k % n_temp

            if num_k == 1:
                num_k = 0
                temp_k = k
            else:

                temp_k = k % n_temp

            total = maxv( temp + temp, temp_k ) + max(sum_temp, 0) * (num_k)

            ans = max(ans, total)


            # print (temp, ans, '|', temp + temp, temp_k, maxv( temp + temp, temp_k ))

    if ans < 0:
        ans = max(c[1:])

    return ans


ans = sol(n, k, p, c)    

print (ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pn = list(map(int, input().split()))
cn = list(map(int, input().split()))

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        if now == start:
            rp = k
            break
    else:
        continue
    if total <= 0:
        continue
    else:
        if k%j==0:
            ans = max(ans, total)
        else:
            s = k%j
            now = start
            total2 = 0
            ans1 =0
            for _ in range(1, s + 1):
                now = pn[now] - 1
                total2 += cn[now]
                ans1 = max(ans1, total2)
            ans2 = ans1 + total * (k//j)
            ans = max(ans, ans2)
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()))
ls = [0]*n
z = 0
l = 0
lv = 0

for i in range(n):
    v = 0
    tmp = i
    cl = deque()
    for j in range(n):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if ls[j] < v or ls[j]==0:
                ls[j] = v
            if tmp in cl:
                if lv < v - c[tmp]:
                    l = len(cl)
                    lv = v - c[tmp]
                break
            cl.append(tmp) 

if k >= n and l > 0:
    z = lv * int(k/l)
    k = k%l
elif k >= n and l == 0:
    z = sum(c) * int(k/n)
    k = k%n

#print(z,ls)

if z > 0 and k != 0:
    print(z+max(ls[:k]))
elif z < 0 and k != 0:
    print(max(ls[:k]))
else:
    print(max(ls))

Submission status: Wrong Answer

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

F=[0]*N
I=[0]*N
CN=[0]*N

for i in range(N):
  around=0
  cnt=0
  A=[]
  if F[i]==0:
    F[i]=1
    around+=1
    cnt+=C[i]
    nex=P[i]-1
    A.append(i)
    while F[nex]==0:
      A.append(nex)
      F[nex]=1
      around+=1
      cnt+=C[nex]
      nex=P[nex]-1
    for j in A:
      I[j]=around
      CN[j]=cnt
#print(F)
#print(I)
#print(CN)
ans=-(10**9)*2
for i in range(N):
  cnt=C[i]
  #動かす回数が一周に満たない時
  if K+1<I[i]:
    d=0
    nex=i
    for j in range(K+1):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  #動かす回数が一周を超えるとき
  elif CN[i]<0:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
  else:
    d=0
    nex=i
    for j in range(I[i]):
      d+=C[nex]
      nex=P[nex]-1
      cnt=max(d,cnt)
    acnt=cnt
    bcnt=C[i]
    syuukai=(K+1)//I[i]
    nokori=(K+1)%I[i]
    syuukai-=1
    nokori+=I[i]
    d=0
    nex=i
    if syuukai>0:
      nokori-=1
    for j in range(nokori):
      d+=C[nex]
      nex=P[nex]-1
      bcnt=max(d,bcnt)
    bcnt+=syuukai*CN[i]
    cnt=max(acnt,bcnt)
  ans=max(ans,cnt)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys

class UnionFind():
  def __init__(self, n):
    self.n = n
    self.parents = [-1] * n

  def find(self, x):
    if self.parents[x] < 0:
      return x
    else:
      self.parents[x] = self.find(self.parents[x])
      return self.parents[x]

  def union(self, x, y):
    x = self.find(x)
    y = self.find(y)

    if x == y:
      return

    if self.parents[x] > self.parents[y]:
      x, y = y, x

    self.parents[x] += self.parents[y]
    self.parents[y] = x

  def size(self, x):
    return -self.parents[self.find(x)]

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

  def members(self, x):
    root = self.find(x)
    return [i for i in range(self.n) if self.find(i) == root]

  def roots(self):
    return [i for i, x in enumerate(self.parents) if x < 0]

  def group_count(self):
    return len(self.roots())

  def all_group_members(self):
    return {r: self.members(r) for r in self.roots()}

  def __str__(self):
    return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N, K = map(int, input().split())

Ps = [0]+list(map(int, input().split()))
Cs = [0]+list(map(int, input().split()))

uf = UnionFind(N+1)
dic = {}

rlt = -sys.maxsize
for i in range(1,N+1):
  uf.union(i,Ps[i])
  
for i in range(1,N+1):
  j = uf.find(i) 
  if j in dic:
    dic[j] += Cs[Ps[i]]
  else:
    dic[j] = Cs[Ps[i]]
    
rlt = -sys.maxsize

for i in range(1,N+1):
  k = uf.find(i)
  cnt = K//uf.size(i)
  md = K % uf.size(i)
  tmp = 0
  if dic[k] > 0:
    tmp = cnt*dic[k]
  tmp2 = Cs[Ps[i]]
  tmp3 = 0
  j = i
  for _ in range(1,md+1):
    j = Ps[j]
    tmp3 += Cs[j]
    tmp2 = max(tmp2, tmp3)
  if tmp2 >= 0 or dic[k] < 0 or cnt == 0:
    tmp += tmp2
  rlt = max(tmp, rlt)
  
print(rlt)

Submission status: Wrong Answer

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

N,K=(int(x) for x in input().rstrip('\n').split())
Ps = [int(x)-1 for x in input().rstrip('\n').split()]
Cs = [int(x) for x in input().rstrip('\n').split()]
res = -10**9-1
for i in range(N):
  next = Ps[i]
  cycle = Cs[next]
  steps =[cycle]
  check = 0
  for _ in range(K):
    next = Ps[next]
    cycle += Cs[next]
    steps.append(cycle)
    if next == i:
      check += 1
      if cycle>0:
        if K%len(steps)!=0:
          now = (K//len(steps))*cycle+max(steps[:K%len(steps)])
          if now>res:
            res = now
          break
        else:
          now =(K//len(steps))*cycle
          if now>res:
            res = now
          break
      else:
        now = max(steps)
        if now>res:
          res = now
        break
  if check ==0:
    now = max(steps)
    if now>res:
      res = now
print(res)

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()))
ls = [0]*n
z = 0
l = 0
lv = 0

for i in range(n):
    v = 0
    tmp = i
    cl = deque()
    for j in range(n):
        if j <= k-1:
            tmp = p[tmp]-1
            v += c[tmp]
            if ls[j] < v or ls[j]==0:
                ls[j] = v
            if tmp in cl:
                if lv < v - c[tmp]:
                    l = len(cl)
                    lv = v - c[tmp]
                break
            #cl.append(tmp) 

if k >= n and l > 0:
    z = lv * int(k/l)
    k = k%l
elif k >= n and l == 0:
    z = sum(c) * int(k/n)
    k = k%n

#print(z,ls)

if z > 0 and k != 0:
    print(z+max(ls[:k]))
elif z < 0 and k != 0:
    print(max(ls[:k]))
else:
    print(max(ls))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
pn = list(map(int, input().split()))
cn = list(map(int, input().split()))

ans = -float('inf')

for i in range(n): #start
    start = i
    now = start
    total = 0
    for j in range(1, k+1):
        now = pn[now]-1
        total += cn[now]
        ans = max(ans, total)
        if now == start:
            if total <= 0:
                break
            else:
                if k%j==0:
                    ans = max(ans, total)
                else:
                    s = k%j
                    now = start
                    for t in range(n): #start
                        now = t
                        total2 = 0
                        ans1=0
                        for _ in range(1, s + 1):
                            now = pn[now] - 1
                            total2 += cn[now]
                            ans1 = max(ans1, total2)
                    ans2 = ans1 + total * (k//j)
                    ans = max(ans, ans2)
print(ans)

Submission status: Wrong Answer

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

N,K=(int(x) for x in input().rstrip('\n').split())
Ps = [int(x)-1 for x in input().rstrip('\n').split()]
Cs = [int(x) for x in input().rstrip('\n').split()]
res = -10**9-1
for i in range(N):
  next = Ps[i]
  cycle = Cs[next]
  steps =[cycle]
  check = 0
  for _ in range(K):
    next = Ps[next]
    cycle += Cs[next]
    steps.append(cycle)
    if next == i:
      check += 1
      if cycle>0:
        if K%len(steps)!=0:
          now = (K//len(steps))*cycle+max(steps[:K%len(steps)])
          if now>res:
            res = now
          break
        else:
          now =(K//len(steps))*cycle
          if now>res:
            res = now
          break
      else:
        now = max(steps)
        if now>res:
          res = now
        break
    if check ==0:
      now = max(steps)
      if now>res:
        res = now
print(res)

Submission status: Wrong Answer

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

N,K=(int(x) for x in input().rstrip('\n').split())
Ps = [int(x)-1 for x in input().rstrip('\n').split()]
Cs = [int(x) for x in input().rstrip('\n').split()]
res = -10**9-1
for i in range(N):
  next = Ps[i]
  cycle = Cs[next]
  steps =[cycle]
  for _ in range(K):
    next = Ps[next]
    cycle += Cs[next]
    steps.append(cycle)
    if next == i:
      if cycle>0:
        if K%len(steps)!=0:
          now = (K//len(steps))*cycle+max(steps[:K%len(steps)])
          if now>res:
            res = now
          break
        else:
          now =(K//len(steps))*cycle
          if now>res:
            res = now
          break
      else:
        now = max(steps)
        if now>res:
          res = now
        break
    if len(steps)==K+1:
      now = max(steps)
      if now>res:
        res = now
print(res)