Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
N, K = map(int, input().split())
*P, = map(int, input().split())
*C, = map(int, input().split())

P = [p-1 for p in P]

used = [0]*N
ans = -float('inf')
for x in range(N):
    if used[x]:
        continue
    used[x] = 1
    Q = [C[x]]

    while not used[P[x]]:
        x = P[x]
        used[x] = 1
        Q.append(C[x])

    M = len(Q)
    acc = list(accumulate(Q*2))
    if acc[M-1] > 0:
        ret = acc[M-1]*(K//M)
        ret += max(acc[K % M+i] - acc[i] for i in range(M))

    else:
        R = Q*2
        ret = -float('inf')
        prev = 0
        cnt = 0
        for i, r in enumerate(R):
            if cnt >= K:
                s -= R[i-K]
                cnt -= 1
            if prev+r > r:
                cnt += 1
                s = prev + r
            else:
                cnt = 1
                s = r
            s = max(r, prev+r)
            ret = max(ret, s)
            prev = s

    if ret > ans:
        ans = ret

print(ans if ans > -float('inf') else max(C))

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
Plist=list(map(int,input().split()))
Clist=list(map(int,input().split()))
def ans(x):
  scr=0
  for i in range(K):
    scr=scr+Clist[Plist[x-1]-1]
    x=Plist[x-1]
  return scr
max=0
for i in range(1,N+1):
  if ans(i)>max:
    max=ans(i)
print(max)

Submission status: Wrong Answer

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

fin = []
L = []
l = 0
for first_index in range(N):
  i = first_index
  if i in fin:
    continue
  L.append([])
  for j in range(N):
    fin.append(i)
    L[l].append(i)
    i = P[i]-1
    if i == first_index:
      break
  l+=1
  
max_s = 0
max_l = []
first_flag = False
for l in L:
  s = sum([C[i] for i in l])
  if max_s < s or not first_flag:
    max_s = s
    max_l = l
    first_flag = True

score = 0
if max_s <= 0:
  max_score = 0
  first_flag = False
  for each_l in L:
    k = len(each_l)-1
    if K < k:
      k = K
    for first_index in each_l:
      s = 0
      i = first_index
      for j in range(k):
        s += C[i]
        i = P[i]-1
        if max_score < s or not first_flag:
          max_score = s
          first_flag = True
  score = max_score
else:
  max_len = len(max_l)
  if K > max_len:
    score = max_s * int(K/max_len)
  k = K%max_len
  max_score = 0
  for first_index in max_l:
    i = first_index
    s = 0
    for j in range(k):
      s += C[i]
      i = P[i]-1
      if max_score<s:
        max_score = s
  score += max_score
print(score)

Submission status: Wrong Answer

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

visit = {i: False for i in range(N)}
Clistlist = []
for i in range(N):
    if not visit[i]:
        visit[i] = True
        Clist = [C[i]]
        curi = P[i]

        while not visit[curi - 1]:
            Clist.append(C[curi - 1])
            visit[curi - 1] = True
            curi = P[curi - 1]
            # Clist.append(C[curi - 1])
        Clistlist.append(Clist)

largest = -1 * (10 ** 9)
# print(Clistlist)

for Clist in Clistlist:
    clen = len(Clist)
    Kd = K % clen
    sum_max = -1 * (10 ** 9)
    # 1loopが負のとき
    if sum(Clist) <= 0:
        for i in range(clen):
            ssum = 0
            for j in range(min(K, clen)):
                ssum += Clist[(i + j) % clen]
                sum_max = max(sum_max, ssum)
    # 1loopが正のとき
    else:
        for i in range(clen):
            # print(Kd, clen)
            ssum = 0
            for j in range(min(Kd, clen)):
                ssum += Clist[(i + j) % clen]
                sum_max = max(sum_max, ssum)
                # print(ssum)
        sum_max += int(K / clen) * sum(Clist)
    # print(sum_max)
    largest = max(largest, sum_max)
print(largest)

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
            b = a
  #print(now,r)
  ans = max(ans,now)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i)-1 for i in input().split()]
C = [int(i) for i in input().split()]
ary=[]
seen=[False]*N
s=[]
for i in range(N):
  if seen[i]:
    continue
  ary.append([0])
  s.append(0)
  while not seen[i]:
    seen[i]=True
    ary[-1].append(ary[-1][-1]+C[i])
    s[-1]+=C[i]
    i=P[i]
  n = ary[-1][-1]
  ary[-1] += [i+n for i in ary[-1][1:]]

ans=max(C)
for i in range(len(ary)):
  a=ary[i]
  length=len(a)//2
  if s[i] > 0:
    tmp = s[i]*(K//length)
    rep = K%length
  else:
    tmp = 0
    rep = min(K,length) 
  for d in range(1, rep+1):
    for j in range(length + 1):
      ans=max(a[j+d]-a[j]+tmp,ans)

print(ans)

Submission status: Wrong Answer

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


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

ans=-1*(10**10)
for i in range(N):
    tmp=0
    pos=i
    gpos=i
    count=0
    while count<K:    
        #print(pos,P[pos])
        tmp+=C[P[pos]-1]
        if tmp>ans:
            ans=tmp
        
        
        pos=P[pos]-1
        count+=1
        if pos==gpos and count!=K:
            divide=K//count-1
            tmp+=tmp*divide
            count+=count*divide
            gpos=10**10
        

print(ans)

Submission status: Wrong Answer

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

import sys
import pprint

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, debug):
		self.debug = debug
	def print(self, *args):
		if self.debug:
			pprint.pprint(args)

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


def main():
	log = Logger(0)
	n, k = map(int, sys.stdin.readline().split())
	p = list(map(int, sys.stdin.readline().split()))
	c = list(map(int, sys.stdin.readline().split()))
	uf = UnionFind(n)
	max_score = -float("inf")
	for i in range(n):
		uf.union(p[i] - 1, i)
	log.print(uf.all_group_members())
	for i in range(n):
		cnt = k
		score = 0
		loopscore = 0
		loop = uf.members(p[i]-1)
		log.print(loop)
		if k > len(loop):
			here = i
			loopsum = 0
			for j in range(len(loop)):
				here = p[here] - 1
				loopsum += c[here]
			assert i == here
			if loopsum > 0:
				score += loopsum * (k // len(loop))
			cnt %= len(loop)
		tmp_max_score = -float("inf")
		here = i
		for j in range(len(loop) - 1):
			if j >= cnt:
				break
			here = p[here] - 1
			score += c[here]
			log.print(here, score)
			tmp_max_score = max(tmp_max_score, score)
		log.print(tmp_max_score)
		max_score = max(tmp_max_score, max_score)
	print(max_score)




	


main()

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:
                j = 0
                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]
                if mod_k != 0:
                    t+= 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:

n, k = map(int, input().split())
k = k+1
p = [0] * n
c = [0] * n
a = [0] * (n+1)
ans = [0] * n

p = list(map(int, input().split()))
c = list(map(int, input().split()))
for i in range(n):
    s = 0
    x = i
    roop = 0
    for j in range(n):
        s += c[x]
        a[j+1] = s
        x = p[x] - 1
        if x == i:
            roop = j + 1
            break
    if s <= 0:
        ans[i] = max(a[1:min(roop+1, k)])
    else:
        if k%roop  == 0:
            ans[i] = max(s * (k // roop) , s * (k // roop - 1) + max(a))
        else:
            ans[i] = max(s * (k // roop) + max(a[:k % roop]), s * (k // roop - 1) + max(a))
print(max(ans))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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]
SB = defaultdict(int)

sumC = sum(C) 

# if sumC > 0:
#   d, k = divmod(k, n)
#   if d > 0:
#     pscore = (d - 1) * sumC
#     k += n 
#   else:
#     pscore = 0
# else:
#   k = min(k, n * 2)
pscore = 0

for p in P: 
  cnt = 0
  score = 0
  mv = - 10 ** 19
  s = p
  while cnt < k:
    score += C[s]
    s = P[s]
    cnt += 1
    mv = max(mv, score)
  
  SB[p] = mv

ans = max(SB.values()) + pscore
print(ans)

print(sumC)

Submission status: Wrong Answer

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

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

    ans.append(max(cand[1:]))


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

Q=[]
uf=UnionFind(N)
for i in range(N):
    uf.union(i,P[i]-1)
D1=list(uf.all_group_members().values())
D2=[]
for i in D1:
    ans=0
    for j in i:
        ans+=C[j]
    D2.append(ans)
L=[len(i) for i in D1]
S=min(2*max(L),K)

for i in range(N):
    ans=-float('inf')
    ans1=0
    now=P[i]-1
    for j in range(S):
        ans1+=C[now]
        now=P[now]-1
        ans=max(ans1,ans)
    Q.append(ans)
    
for i,value in enumerate(D2):
    if value>0:
        ans3=value*(K//L[i])
        for j in D1[i]:
            ans=-float('inf')
            ans1=0
            now=P[j]-1
            for k in range(K%L[i]):
                ans1+=C[now]
                now=P[now]-1
                ans=max(ans1,ans)
            Q.append(ans3+ans)
print(max(Q))

Submission status: Wrong Answer

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

k = 0
score_list = []
for i in range(N):
  start_position = i
  position = i
  score = 0
  for k in range(K):
    position = P[position] - 1
    score += C[position]
    score_list.append(score)

    if start_position == position:
      if score > 0:
        break
        
print(max(score_list))

Submission status: Wrong Answer

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

n=0
loops=[]
loops_score=[]
searched=[False]*N
sum_len=0

for _ in range(N):
    n=searched.index(False)
    l=[]
    ls=[]
    for i in range(N):
        n=P[n]-1
        searched[n]=True
        if n in l:
            break
        l.append(n)
        ls.append(C[n])
    
    loops.append(l)
    loops_score.append(ls)
    sum_len+=len(l)
    if sum_len==N:
        break
    
#print(loops)
#print(loops_score)

ans=-1*float('inf')

for scores in loops_score:
    ans_=0
    ls=len(scores)
    scores_sum=sum(scores)
    
    if K>ls and scores_sum>0:
        ans_loop=scores_sum*(K//ls)
    else:
        ans_loop=0
        
    maxlen=min(K,ls)
    #print(maxlen)
    ex_scores=scores+scores[:-1]
    #print(ex_scores)
    le=ls*2-1
    
    ruiseki=[0]*(le+1)
    for i in range(1,le+1):
        ruiseki[i]=ruiseki[i-1]+ex_scores[i-1]
    #print(ruiseki)
    
    ans_=max(scores)
    
    if K>=2:
        for d in range(2,maxlen+1):
            for j in range(le+1-d):
                ans_=max(ans_,ruiseki[j+d]-ruiseki[j])
                #print(scores[j:j+d])
                #print(le,d,j,ans_+ans_loop)
                if d==maxlen:
                    break
    ans=max(ans,ans_+ans_loop)
        
print(ans)

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, len(lst)):
                    for start in range(len(lst)):
                        num = (k - interval) // 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)
                """
                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:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

class Doubling:
    def __init__(self, lst, max_step):
        self.lst = lst
        self.max_step = max_step
        self.k = int(log2(max_step * 2 - 1)) + 1
        # print(self.k)
        self.D = self.create()

    def create(self):
        len_ = len(self.lst)
        D = [[-1] * len_ for _ in range(self.k)]
        D[0] = self.lst
        d = 2
        for i in range(1, self.k):
            for j in range(len_):
                D[i][j] = D[i - 1][D[i - 1][j]]
            d *= 2
        # print(D)
        return D

    def step(self, start, step):
        v = start
        for i in range(self.k, -1, -1):
            l = 1 << i
            if l <= step:
                v = self.D[i][v]
                # print(i, l)
                step -= l
        return v

def solve():
    N, K = MI()
    P = LI1()
    C = LI()

    ans = -INF
    for i in range(N):
        S = [0] * (N+1)
        used = [0] * N
        used[i] = 1
        mxs = [-INF] * (N+1)
        step = 0
        while 1:
            next = P[i]
            step = step + 1
            score = S[step-1] + C[next]
            S[step] = score
            mxs[step] = max(mxs[step-1], score)
            # ans_l = max(ans_l, S[step])
            if step == K:
                # print(mxs, mxs[K])
                ans = max(ans, mxs[K])
                break
            if used[next]:
                left = K - step
                # print(next, S, step, S[step], left)
                p = left // step
                q = left % step
                # print(mxs, p, q, mxs[step])
                # 現在の最高得点で打ち切る
                ans = max(ans, mxs[step])

                # さらにスコアを伸ばす
                if p > 0:
                    ans = max(ans, S[step] + max(0, mxs[step]))
                    ans = max(ans, S[step] * (p+1) + max(0, mxs[q]))
                else:
                    ans = max(ans, S[step] + max(0, mxs[q]))

                # plus = max(S[step] * p + max(0, mxs[q]), mxs[step])
                # ans = max(ans, max(mxs[step], S[step] + mxs[step] * p + mxs[q]))
                # ans = max(ans, max(mxs[step], S[step] + max(0, plus)))
                break
            used[next] = 1
            i = next
    print(ans)

    
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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

seen = [0] * N

ans = -10**20

for i in range(N):
    if not seen[i]:
        seen[i] = 1
        loop = [C[i]]
        while True:
            i = P[i]
            if seen[i]:
                break
            seen[i] = 1
            loop.append(C[i])
        L = len(loop)
        loop = loop + loop
        loop = [0] + list(accumulate(loop))
        if loop[L] <= 0:
            move = min(L, K)
            for i in range(L):
                for j in range(1, move + 1):
                    ans = max(ans, loop[i + j] - loop[i])
        else:
            if K > L:
                div, mod = divmod(K, L)
                tmp = div * loop[L]
                move = min(mod, L)
                if move:
                    for i in range(L):
                        for j in range(1, move + 1):
                            ans = max(ans, tmp + loop[i + j] - loop[i])
                else:
                    ans = max(ans, tmp)
                tmp = (div - 1) * loop[L]
                move = L
                for i in range(L):
                    for j in range(1, move + 1):
                        ans = max(ans, tmp + loop[i + j] - loop[i])
            else:
                continue
                move = K
                for i in range(L):
                    for j in range(1, move + 1):
                        ans = max(ans, tmp + loop[i + j] - loop[i])

print(ans)

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**20)
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)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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):
    ret = defaultdict(list)
    for i in range(self.n):
      ret[self.find(i)].append(i)
    return ret

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

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

uf = UnionFind(N)

for i in range(N):
  uf.union(i, P[i])

D = uf.all_group_members()
E = defaultdict(list)
F = defaultdict(int)

Num = [0]*N

for root in uf.roots():
  i = root
  n = 0
  E[root].append(0)
  while P[i] != root:
    i = P[i]
    n += 1
    Num[i] = n
    E[root].append(E[root][-1] + C[i])
  E[root].append(E[root][-1] + C[root])
  F[root] = n + 1
  #追加分
  i = root
  while P[i] != root:
    i = P[i]
    E[root].append(E[root][-1] + C[i])
  E[root].append(E[root][-1] + C[root])

#print(Num, E, F)
ans = 0

for root, L in E.items():
  loop, k = divmod(K, F[root])
  if k == 0:
    loop -= 1
    k += F[root]
  temp = 0
  if L[-1] >= 0:
    temp += (L[-1]//2) * loop
  for i in range(F[root]):
    for j in range(i+1, i+k+1):
      ans = max(ans, temp + E[root][j] - E[root][i])

print(ans)

Submission status: Wrong Answer

Solution code:
nk=input("").split(" ")
n=int(nk[0])
k=int(nk[1])
lisp=input("").split(" ")
lisc=input("").split(" ")
p=[]
c=[]
plis=[]
for i in range(n):
    p+=[int(lisp[i])-1]
    c+=[int(lisc[i])]
    plis+=[1]
cycle=[]
cyp=[]
cyc=[]


for i in range(n):
    
    
        np=p[i]
        cys=c[i]
        
        cyct=[c[i]]
        while(np!=i):
            
            cys+=c[np]
            
            cyct+=[cys]
            np=p[np]
        cycle+=[cys]
        
        cyc+=[cyct]
        print(1)
if(max(cycle)<=0):
    m=max(cyc[0])
    
    for i in cyc:
        if(m<max(i)):
            m=max(i)
    print(m)
elif(k>n+2):
    m=[cycle[0],len(cyc[0])]
    t=[0]
    
    for i in range(n):
        if(m[0]*len(cyc[i])<cycle[i]*m[1]):
            m=[cycle[i],len(cyc[i])]
            t=[i]
        elif(m[0]*len(cyc[i])==cycle[i]*m[1]):
            t+=[i]
    lll=len(cyc[t[0]])
    for i in t:
        if(lll<len(cyc[i])):
            lll=len(cyc[i])
    syou=(k-1)//lll
    amari=(k-1)%lll
    ten=syou*cycle[i]
    tama=0
    
    for i in t:
        syo=amari//len(cyc[i])
        if(tama<syo*cycle[i]+cyc[i][amari%len(cyc[i])]):
            tama=syo*cycle[i]+cyc[i][amari%len(cyc[i])]
            
    print(ten+tama)
else:
    t=0
    for i in range(n):
        cc=c[i]
        ccc=[cc]
        np=p[i]
        
        for kws in range(k):
                cc+=c[np]
                
                np=p[np]
                ccc+=[cc]
        
        if(t<max(ccc)):
            t=max(ccc)
    print(t)