Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

Solution code:
import math
x=input()
x0=x.split()
n=int(x0[0])
k=int(x0[1])
p=input()
p=[int(n) for n in p.split()]
c=input()
c=[int(n) for n in c.split()]
if k<n or sum(c)<=0:
    m=-(10**9)
    for i in range(n):
        for l in range(min(k,n)):
            o=i
            s=0
            for j in range(l+1):
                o=p[o]-1
                s+=c[o]
            if m<s:
                m=s
    print(m)
else:
    m=-(10**9)
    x=0
    for i in range(n):
        for l in range(2*n):
            o=i
            s=0
            for j in range(l+1):
                o=p[o]-1
                s+=c[o]
            if m<s:
                m=s
                x=l+1
    mm=-(10**9)
    for i in range(n):
        for l in range(k-math.floor(k/x)*x):
            o=i
            s=0
            for j in range(l+1):
                o=p[o]-1
                s+=c[o]
            if mm<s:
                mm=s
    print(m*math.floor(k/x)+mm)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
pl = list(map(int, input().split())) 
cl = list(map(int, input().split())) 


resu = -10**10
for i in range(n):
    dp =[True]*n
    temp = i
    kari = 0
    kaisu = 0
    res = -10**10
    while dp[temp] and kaisu <= k:
        dp[temp] =False
        now = pl[temp]-1
        kari += cl[now] 
        temp = now
        kaisu +=1
        res = max(res,kari)
    if dp[temp]==False and kaisu<= k:
        if kari >=0:
            m = k // kaisu
            if k % kaisu ==0:
                m -=1
            resu = max(resu,res+kari*m)
    resu = max(resu,res)

print(resu)

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,(syuukai)*CN[i])
  ans=max(ans,cnt)
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()))





root = []
root_c = []#累積和

for j in range(n):
    root.append([])
    root_c.append([0])
    now = j
    for i in range(n):
        root_c[j].append(root_c[j][i] + c[now])
        root[j].append(c[now])
        now = p[now]-1
        

#スコア計算
scores = []
roop = k // n
rest = k - (n*roop)

for i in range(len(root)):
    print(root_c[i][:rest+1])
    scores.append(sum(root[i])*roop + max(root_c[i][:rest+1]))
        
        
ans = -float('inf')
for i in range(len(scores)):
    if ans < scores[i]:
        ans = scores[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()))

dummy=set()
loop=[]
X=set(range(N))
while len(dummy)!=N:
  a=[]
  k=min(X-dummy)
  a.append(k)
  dummy.add(k)
  l=P[k]-1
  while l!=k:
    a.append(l)
    dummy.add(l)
    l=P[l]-1
  loop.append(a)

ans=-(10**300)
for l in loop:
  temp=0
  s=len(l)
  ssum=0
  k=0
  for i in range(s):
    ssum+=C[l[i]]
  if ssum>0:
    temp+=(K%s)*ssum
    k=K-(K%s)
  else:
    k=min(K,s)
  kmax=-(10**300)
  for ii in range(1,k):
    for jj in range(s):
      tempscore=temp
      for kk in range(ii):
        tempscore+=C[l[(jj+kk)%s]]
      if tempscore>kmax:
        kmax=tempscore
  if kmax>ans:
    ans=kmax
print(ans)

Submission status: Wrong Answer

Solution code:
# O(EV)
def bellman_ford(s):
    d = [0]*n # 各頂点への最小コスト
    d[s] = 0 # 自身への距離は0
    x=s
    visited=[x]
    for tt in range(k):
        update = False # 更新が行われたか
        aa,bb,cc=g[x][0],g[x][1],g[x][2]
        if d[bb] < d[aa] + cc:
                d[bb] = d[aa] + cc
                update = True
                visited+=[bb]
            
        if not update:
            break

        if visited[0]==visited[-1]:
            if d[visited[-1]]>=0:
                pin=len(visited)-1
                d[visited[0]]=(k//pin+1)*d[visited[0]]

                x=s

                for tt in range(k%pin):
                  update = False # 更新が行われたか
                  aa,bb,cc=g[x][0],g[x][1],g[x][2]
                  
                  d[bb] = d[aa] + cc

                  rr=10**30

                  for ss in d:
                      if ss!=0:
                          rr=min(rr,ss)

                  return [rr]

                
                



        x=bb
    return d

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

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

if max(c)<0:
    print(max(c))
    exit()

for i in range(n):
    g.append((i,p[i]-1,c[p[i]-1]))

ans=0

for i in range(n):
  ans=max(ans,max(bellman_ford(i)))

print(ans)

Submission status: Wrong Answer

Solution code:


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

parent = [-1] * N


def union(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        return
    parent[x] = y

def find(x):
    if parent[x]  == -1:
        return x
    else:
        res = parent[x] = find(parent[x])
        return res

for i, p in enumerate(P):
    union(i, p)

As = [[] for _ in range(N)]
for i, c in enumerate(C):
    As[find(i)].append(c)


def get_point(A, size):
    n = len(A)
    if n > size:
        cur = left = 0
        res = max(A)
        for right, a in enumerate(A):
            cur += a
            while right - left > size:
                cur -= A[left]
                left += 1
            if right - left < size:
                res = max(cur, res)
    else:
        res = max(A)
        cur = 0
        for a in A:
            cur = max(cur + a, a)
            res = max(res, cur)
        total = sum(A)
        if total > 0:
            repeat, rest = divmod(size, n)
            a = total * repeat
            i = 0
            j = n - 1
            temp = 0
            res = max(res, a)
            while i + n - j  <= rest:
                if A[i] > A[j]:
                    temp += A[i]
                    i += 1
                else:
                    temp += A[j]
                    j -= 1
                res = max(res, a + temp)
    return res

res = max(C)
for A in As:
    if A:
        res = max(res, get_point(A, K))
print(res)

Submission status: Wrong Answer

Solution code:
n,k=list(map(int, input().split()))
p=list(map(int, input().split()))
c=list(map(int, input().split()))
z=-10000000000000
lin=[0]*n
lstart=[]
llen=[]
loopsum=[]
loopstructure=[]
stsc=[]
for i in range(n):
    if lin[i]==0:
        lstart.append(i)
        d=i
        f=0
        v=0
        strc=[i]
        sc=[c[i]]
        while lin[d]==0:
            lin[d]=1
            d=p[d]-1
            strc.append(d)
            sc.append(c[d])
            f+=1
            v+=c[d]
            if i==d :
                llen.append(f)
                loopsum.append(v)
                loopstructure.append(strc)
                stsc.append(sc)                
for j in range(len(stsc)):
    o=len(stsc[j])-1
    x=-10000000000000
    y=-10000000000000
    q=min(o,k)
    for i in range(o):
        for ii in range(1,k+1):
            if i+ii<o:
                ny=sum(stsc[j][i:i+ii])
            else:
                ny=sum(stsc[j][0:i+ii-o]+stsc[j][i:o])
            if ny>y:
                y=ny

                
    nz=max((k//o)*loopsum[j]+y,y)
    if nz>z:
        z=nz
print(z)

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()]
p = float('inf')
score=ans=0

for i in range(N):
    p = P[i]-1
    for n in range(K):
        score += C[p]
        p = P[p]-1
        if score >0:
            ans = max(ans, score)
        else:
            if ans ==0:
                ans = float('inf')
            ans = -min(abs(ans),abs(score))
    score = 0

print(ans)

Submission status: Wrong Answer

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

pList = list(map(int,input().split()))

cList = list(map(int,input().split()))

cSum = sum(cList)

ans = 0
p = {}
c = {}

for i in range(n):
    p[i] = pList[i]
    c[i] = cList[i]

highScore = min(cList)
for i in range(n):
    count = 0
    zahyou = i
    score = 0
    zumi =set()
    while count < k:
        if zahyou in zumi:
            if score > 0:
                score += score * ((k // count) - 1)
                count += ((k // count) - 1) * count
            else:
                break
        zumi.add(zahyou)
        zahyou = p[zahyou] - 1
        score += c[zahyou]
        count += 1
        if highScore < score:
            highScore = score


print(ans+highScore)

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 = [0] + P
C = [0] + C

ans = -10**17
Loop = []
LoopValue = []
LoopCount = []

for i in range(1, n+1):
    if i in []:
        pass
    else:
        Visited = []
        Value = [0]
        count = 0
        pos = P[i]
        while pos != i:
            Visited.append(pos)
            Value.append(Value[-1] + C[pos])
            count += 1
            pos = P[pos]
        Visited.append(i)
        count += 1
        Value.append(Value[-1] + C[pos])
        Loop.append(Visited)
        LoopValue.append(Value)
        LoopCount.append(count)
        
        
        if k//count == 0:
            tmp = max(Value[1:k%count + 1])
        else:
            tmp = max(max(Value), k//count*Value[-1] + max(Value[:k%count + 1]))
        ans = max(tmp, ans)
print(ans)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
P=[int(_) - 1  for _ in input().split()]
C=list(map(int,input().split()))
end_flag=[0]*N
def calc(pos):
  X = [-1 for _ in range(N)]
  X2 = [-1 for _ in range(N)]
  k=0
  p=pos
  score=0
  ans=-1000000000
  X[p]=0
  X2[p]=0
  while k<K:
    p=P[p]
    score+=C[p]
    k+=1
    if X[p]!=-1:
      move_skip=max((K-k)//(k-X[p])-1,0)
      score+=(score-X2[p])*move_skip
      k+=move_skip*(k-X[p])
      
    X[p]=k
    X2[p]=score
    ans=max(score,ans)
  last_p=p
  p=i
  while end_flag[p]==0:
    p=P[p]
    score-=C[p]
    last_p=P[last_p]
    score+=C[p]
    ans=max(score,ans)
    end_flag[p]=1
  end_flag[i]=1
  return ans
final_ans=-10000000


for i in range(N):
  if end_flag[i]:continue
  final_ans=max(calc(i),final_ans)
  
print(final_ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
datp = list(map(lambda x: int(x) - 1, input().split()))
datc = list(map(int, input().split()))
cur = 0
total = 0
sdat = []
finalres = -99999999999999


def kadane(ary):
    if len(ary) == 0:
        return -9999999999
    n = len(ary)
    dp = [0] * (n + 1)
    for i in range(n):
        dp[i] = dp[i - 1] + ary[i]
    if max(dp) == 0:
        return max(ary)
    return max(dp)

used = [False] * n
for start in range(n):
    cur = start
    cost = []
    while used[cur] is False:
        ne = datp[cur]
        used[cur] = True
        cost.append(datc[ne])
        cur = ne

    finalres = max(finalres, kadane(cost))



# movetalbeは next, scoreの遷移
movetable = []
for i in range(35):
    movetable.append([None] * n)

for i in range(n):
    ne = datp[i]
    score = datc[ne]
    movetable[0][i] = [ne, score]

for loop in range(1, 35):
    for i in range(n):
        next1, score1 = movetable[loop - 1][i]
        next2, score2 = movetable[loop - 1][next1]
        movetable[loop][i] = [next2, score1 + score2]

# print(movetable)
kres = []


kk = k
# print("k", kk)
for i in range(n):
    # i start
    cur = i
    score = 0
    for i in range(35):
        if ((kk >> i) & 1) == 1:
            cur, addscore = movetable[i][cur]
            score += addscore
    finalres = max(finalres, score)

print(finalres)

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
		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)):
			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:
n,k = map(int, input().split(' '))
p = list(map(int, input().split(' ')))
c = list(map(int, input().split(' ')))

import numpy as np
p = np.asarray(p, dtype=np.int)-1
c = np.asarray(c, dtype=np.int)

cost = []
p_set = set(p)
while len(p_set) != 0:
    buf = []
    cos = []
    v = min(p_set)
    for _ in range(n):
        if v in buf:
            break
        buf.append(v)
        v = p[v]
        cos.append(c[v])
    cost.append(cos)
    p_set -= set(buf)
    
scores = []
for cc in cost:
    lc = len(cc)
    if lc < k:
        kk = k % lc
        if sum(cc) > 0:
            nn = k // lc
        else:
            nn = 0
    else:
        kk = k
        nn = 0
    score = sum(cc) * nn
    if kk != 0:
        ccc = cc * 2
        buf = sum(cc[:kk])
        for kkk in range(1, kk+1):
            for i in range(lc):
                if buf < sum(cc[i:kkk+i]):
                    buf = sum(cc[i:kkk+i])
        score += buf
    scores.append(score)
    
print(max(scores))

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_max[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())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
ans=-10**10
for st in range(N):
	now = st+1
	temp=[0]
	while(P[now-1] != st+1):
		temp.append(temp[-1]+C[P[now-1]-1])
		now = P[now-1]
	temp.append(temp[-1]+C[P[now-1]-1])
	if len(temp)>=K+1:
		ans=max(ans, max(temp[1:K+1]))
		continue
	if temp[-1]<=0:
		ans = max(ans, (max(temp[1:])))
	else:
		t=temp[-1]*(K//(len(temp)-1))
		t+=max(temp[:2+K%(len(temp)-1)])
		ans=max(ans, t)
		
print(int(ans))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))
for i in range(n):
  P[i] -= 1
l = k
ans = -float('inf')
for i in range(n):
  k = l
  loop = 1
  w = P[i]
  while w != i:
    w = P[w]
    loop += 1
  
  base = 0
  w = i
  for j in range(loop):
    w = P[w]
    base += C[w]
  
  base = max(0, base*(k//loop))
  k = k%loop
  if k == 0:
    k += loop
    base = max(0, base*(k//loop-1))
    
  score = 0
  w = i
  res = -float('inf')
  for j in range(k):
    w = P[w]
    score += C[w]
    res = max(max(C[P[i]], score), res)
  
  res += base
 
  ans = max(ans, res)
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
import sys

input = sys.stdin.buffer.readline

n, k = map(int, input().split())
P = list(map(int, input().split()))
C = list(map(int, input().split()))

kouho = []

used = [False] * (n)
for i in range(n):
    if used[i]:
        continue
    now = i
    cnt = 0
    res = 0
    route = []
    while True:
        if used[now]:
            break
        route.append(C[P[now] - 1])
        used[now] = True
        nex = P[now] - 1
        cnt += 1
        res += C[nex]
        now = nex
    kouho.append((res, cnt, route))

ans = -(10 ** 20)
for res, cnt, route in kouho:
    temp1 = 0
    num = len(route)
    kaisu = 0
    if k >= cnt:
        if res > 0:
            temp1 += res * (k // cnt)
            kaisu = k % cnt
        else:
            kaisu = num
    else:
        kaisu = k
    temp2 = -(10 ** 20)
    route += route
    ACR = list(accumulate([0] + route))
    for i in range(num):
        for j in range(1, kaisu + 1):
            temp3 = ACR[j + i] - ACR[i]
            temp2 = max(temp2, temp3)
            # print((i, j), temp3)
    # print(temp1)
    ans = max(ans, temp1 + temp2)
    if res > 0 and k >= cnt:
        temp1 = 0
        for i in range(num):
            for j in range(1, num + 1):
                temp3 = ACR[j + i] - ACR[i]
                temp2 = max(temp2, temp3)
                # print((i, j), temp3)
        ans = max(ans, temp1 + temp2)

print(ans)

Submission status: Wrong Answer

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

ans = max(C)
for i in range(N):
    s = i
    l = []
    while True:
        s = P[s]-1
        l.append(C[s])
        if s == i:
            break
    if sum(l) > 0:
        c = K//len(l)*sum(l)
        n = K%len(l)
        ans = max(ans,c)
        s = i
        x = 0
        for j in range(n):
            s = P[s]-1
            x += C[s]
            ans = max(ans,c+x)

    n = min(N,K)
    s = i
    x = 0
    for j in range(n):
        s = P[s]-1
        x += C[s]
        ans = max(ans,x)
            
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()))

score = [0 for _ in range(n)]
loopn = [0 for _ in range(n)]
done = {i: True for i in range(n)}
for start in range(n):
    if done[start]:
        nex = -1
        j = 0
        tuuka = []
        nax = -float("inf")
        while nex != start:
            if nex == -1:
                nex = P[start]-1
            else:
                nex = P[nex]-1
            tuuka.append(nex)
            score[start] += C[nex]
            nax = max(nax, score[start])
            j += 1
        loopn[start] = j
        for i in tuuka:
            done[i] = False
            loopn[i] = j
            score[i] = score[start]
            nokori = k-(k//loopn[start])*loopn[start]
    else:
        nax = 0
    if score[start] < 0:
        score[start] = nax
    else:
        score[start] = (k//loopn[start])*score[start]
        nokori = k-(k//loopn[start])*loopn[start]
        i = 0
        nnnnn = (k//loopn[start])
        nscore = 0
        nax = 0
        while i < nokori:
            nex = P[nex]-1
            nscore += C[nex]
            if nscore < 0:
                break
            nax = max(nax, nscore)
            i += 1
        if nax > 0:
            score[start] += nax


ans = max(score)
if ans <= 0:
    ans = max(C)
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
ans = -10**9
for i in range(n):
    scores = [0]
    seen = set([i])
    now = i
    loop = False
    for _ in range(k):
        now = p[now]-1
        scores.append(c[now])
        if now in seen:
            loop = True
            break
        seen.add(now)
    for i in range(len(scores)-1):
        scores[i+1] += scores[i]
    tmp = max(scores[1:])
    ans = max(ans, tmp)
    if (not loop) or scores[-1]<=0:
        continue
    tmp = scores[-1]*(k//(len(scores)-1))
    rem = k%(len(scores)-1)
    tmp += max(scores[:rem+1])
    ans = max(ans, tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import numpy as np


def solve(N: int, K: int, P: "List[int]", C: "List[int]"):
    ans = -10**10
    tbl = np.zeros((N,N))
    for i in range(N):
        move = 0
        score = 0
        p_start = i+1
        p_current = p_start
        p_next = -1
        for j in range(min(N, K)):
            move += 1
            p_next = P[p_current-1]
            score += C[p_next-1]
            p_current = p_next
            tbl[i][j] = score
    #print(tbl)
    if N>K:
        print(int(tbl.max()))
    else:
        mm = K % N
        if mm>0:
            last_v = [int(tbl[i][-1]+tbl[i][mm-1]) for i in range(N)]
        else:
            print(int(tbl.max()))
            return
        print(max(last_v))
    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:
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 = -float("inf")

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):
      ans = max(ans, temp + E[root][j] - E[root][i])

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n,k = map(int, input().split())
    p = [int(v)-1 for v in input().split()]
    c = [int(v) for v in input().split()]
    groups = []
    nums = set(list(range(n)))
    while len(nums)>0:
        num = nums.pop()
        s = set([num])
        nn = num
        while p[nn] != num:
            s.add(p[nn])
            nn = p[nn]
            nums.remove(nn)
        groups.append(s)
    # print(groups)
    
    ans = -(1<<63)
    for s in groups:
        cnt = len(s)
        sl = list(s)
        sl2 = sl+sl
        mul = k // cnt
        cnt2 = k % cnt
        if mul>0:
            mul -= 1
            cnt2 += cnt
        ss0 = [0] * (cnt2+1)
        for c2 in range(1,cnt2+1):
            if mul>0:
                add = sum([c[i] for i in s])*mul
                if add<0:
                    add = 0
            else:
                add = 0
            
            # print(cnt, sl, [c[i] for i in sl], add, c2, ans)
            ss = [0] * cnt
            ss0[c2] = ss0[c2-1] + c[sl2[c2-1]]
            ss[0] = ss0[c2] + add
            ans = max(ans, ss[0])
            for i in range(1,cnt):
                # print('n',ss[i-1],c[sl[i-1]],c[sl[(i-1+c2)%cnt]], i, (i-1+c2)%cnt)
                ss[i] = ss[i-1]-c[sl[i-1]]+c[sl[(i-1+c2)%cnt]]
                ans = max(ans, ss[i])
            # print(ss)
        # print(ss0)
    print(ans)

main()