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


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    N, K = read_ints()
    P = [p-1 for p in read_ints()]
    C = read_ints()

    max_score = -math.inf
    for i in range(N):
        cycle_score = C[i]
        scores = [0, C[i]]
        j = P[i]
        k = K
        while k > 1 and i != j:
            cycle_score += C[j]
            scores.append(cycle_score)
            j = P[j]
            k -= 1
        cycle_size = len(scores)-1
        cycle_count = K//cycle_size
        max_score = max(max_score, max(scores[1:]))
        if k > 1:
            max_score = max(max_score, cycle_score*cycle_count+max(scores[:K%cycle_size+1]))
    return max_score


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

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

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

p=list(map(int,input().split()))
p=[q-1 for q in p]
# 順列
c=list(map(int,input().split()))

ppp=p[:]
ans=max(c)

        
if k<=n:
    # kこのループを作る
    for i in range(n):
        nxt=p[i]
        now=0
        for j in range(k):
            nxt=p[nxt]
            now+=c[nxt]
            ans=max(ans,now)
    print(ans)
    exit()


# ループを発見したい
# from pprint import pprint

loopcnt=[]
visited=[]

for i in range(n):
    first=p[i]
    if first in visited:
        continue
    now=first
    vs=set([now])
    for j in range(n):
        now=p[now]
        if now in visited:
            continue
        visited.append(now)
        if now in vs:
            loopcnt.append(vs)
            continue
        vs.add(now)
        
lll=[]
for item in loopcnt:
    point=0
    for v in item:
        point+=c[v]
        
    lll.append((list(item),point))
# print(lll)
anslist=[]
for sss,ppp in lll:
    # print(sss,ppp)
    ls=len(sss)
    if ppp<=0:
        # ans=0
        for i in range(ls):
            now=sss[i]
            point=0
            for j in range(ls):
                now=p[now]
                point+=c[now]
                ans=max(ans,point)
        anslist+=(ans),
    else:
        # ans=0
        for i in range(ls):
            now=sss[i]
            point=0
            for j in range(k%ls):
                now=p[now]
                point+=c[now]
                ans=max(ans,point)
        anslist+=(ans+ppp*(k//ls)),
        
print(max(anslist))

Submission status: Wrong Answer

Solution code:
import numpy as np

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

info = np.array([[P[i], C[i]] for i in range(N)])

ans = []
for n in range(N):
    k = 0
    score = 0
    next_ = info[n,0]
    while k < K:
        score += info[next_-1, 1]
        ans.append(score)
        next_ = info[next_-1, 0]
        k += 1
        if next_-1 == n:
            score *= K//k
            k *= K//k

print(max(ans))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7


def debug(*x):
    print(*x, file=sys.stderr)


def solve(N, K, PS, CS):
    PS = [x - 1 for x in PS]
    CS = [CS[PS[i]] for i in range(N)]
    PSS = [PS]
    CSS = [CS]
    prevPS = PS
    prevCS = CS
    for i in range(30):
        PS2 = [prevPS[prevPS[i]] for i in range(N)]
        CS2 = [prevCS[i] + prevCS[prevPS[i]] for i in range(N)]
        PSS.append(PS2)
        CSS.append(CS2)
        prevPS = PS2
        prevCS = CS2

    score = [0] * N
    pos = list(range(N))
    length = [0] * N
    maxbit = K.bit_length() - 1
    for i in range(maxbit, -1, -1):
        # debug(": i", i)
        # debug(": 2**i", 2**i)
        # debug(": CSS[i]", CSS[i])
        # debug(": PSS[i]", PSS[i])
        # debug(": score", score)
        # debug(": length", length)
        for j in range(N):
            # debug(": length[j] + 2 ** i <= K", length[j] + 2 ** i <= K)
            # debug(": CSS[i][pos[j]]", CSS[i][pos[j]])
            if length[j] + 2 ** i <= K and CSS[i][pos[j]] > 0:
                # debug("add: j", j)
                score[j] += CSS[i][pos[j]]
                pos[j] = PSS[i][pos[j]]
                length[j] += 2 ** i
            # if CSS[i][j] > score[j]:
            #     # debug("reset: j", j)
            #     # debug(": CSS[i][i], score[j]", CSS[i][i], score[j])
            #     pos[j] = PSS[i][j]
            #     score[j] = CSS[i][j]
            #     length[j] = 2 ** i

    # debug("finish: score", score)
    ret = max(score)
    if ret == 0:
        ret = max(CS)
    return ret


def main():
    # parse input
    N, K = map(int, input().split())
    PS = list(map(int, input().split()))
    CS = list(map(int, input().split()))
    print(solve(N, K, PS, CS))


# tests
T1 = """
5 2
2 4 5 1 3
3 4 -10 -8 8
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
8
"""

T2 = """
2 3
2 1
10 -7
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
13
"""

T3 = """
3 3
3 1 2
-1000 -2000 -3000
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
-1000
"""

T4 = """
10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
29507023469
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

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


for i in c:
    if i >= 0:
        break
else:
    print(max(c))
    exit()

p.insert(0,0)
c.insert(0,0)
ans = 0
for i in range(1,n+1):
    visited = [0 for _ in range(n+1)]
    tmp = i
    tmp_ans = 0
    cnt = 0
    while cnt <= k:
        nxt = p[tmp]
        if visited[nxt] == 0:
            visited[nxt] = 1
            tmp_ans += c[nxt]
        else:
            if tmp_ans > 0:
                tmp_ans += tmp_ans*((k-cnt)//cnt)#何周かできるなら
                ans = max(ans,tmp_ans)
                for j in range(k%cnt):#端数分
                    tmp_ans += c[nxt]
                    nxt = p[nxt]      
                    ans = max(ans,tmp_ans)              
            break
        ans = max(ans,tmp_ans)
        cnt += 1
        tmp = nxt

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 21:20:49 2020

@author: NEC-PCuser
"""

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

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

X = [0] * N
c_li = []
position = 0 
sum_li = []
for i in range(len(P)):
	if X[i] == 1:
		continue
	position = i
	li = []
	sum_l = 0
	for j in range(len(P)):
		X[position] = 1
		li.append(C[position])
		position = P[position] - 1
		sum_l += C[position]
		if position == i:
			c_li.append(li)
			sum_li.append(sum_l)
			break
ans = -1000000001
m = 0
for x_li in c_li:
	q = K % len(x_li)
	if q == 0:
		q = len(x_li)
	r = K // len(x_li)
	max_score = -1000000001
	for i in range(0, len(x_li)):
		k = i
		score = 0
		for j in range(q):
			score += x_li[k]
			if max_score < score:
				max_score = score
			k += 1
			if len(x_li) == k:
				k = 0
	sum_c = sum_li[m]
	m += 1
	if (sum_c > 0):
		if ans < max_score + r * sum_c:
			ans = max_score + r * sum_c
	else:
		if ans < max_score:
			ans = max_score
		
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = [0] + list(map(int, input().split()))
c = [0] + list(map(int, input().split()))
arr = list(range(1, n+1))
res = max(c[1:])
for i in arr:
    tmp = []
    tmp_res = 0
    cnt = 0
    while cnt < k:
        i = p[i]
        tmp_res += c[i]
        cnt += 1
        res = max(res, tmp_res)
        if i in tmp:
            break
        tmp.append(i)
print(res)

Submission status: Wrong Answer

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

def max2(x,y):
    return x if x > y else y

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

res = 0
off = max(C)
m2 = off
for i in range(N):
    tmp = 0
    m1 = off
    l = i
    S = 0
    for j in range(N):
        l = P[l] - 1
        S += C[l]
        if l==i:
            k = j+1
            break
    cnt = K // k - (K % k == 0)
    l = i
    for j in range(k):
        tmp += C[l]
        m1 = max2(m1, tmp)
        l = P[l] - 1
    if S > 0:
        m1 += cnt*S
    m2 = max2(m1, m2)

print(res + m2)
"""
4 10
2 3 4 1
1 2 3 4
"""

Submission status: Wrong Answer

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

ans=-float('inf')

def get_loop_score(start): # return loop len and its loop score
    now_p=0
    visited=set()
    nxt=p[start]-1

    while True:
        nxt=p[nxt]-1
        if nxt in visited:
            break
        visited.add(nxt)
        now_p+=c[nxt]
    return now_p

def simulate(start,nokori): # ret max possible score
    now_p=0
    nxt=p[start]-1
    cnt=0
    p_lis=[]


    while True:
        nxt=p[nxt]-1
        visited.add(nxt)
        now_p+=c[nxt]
        p_lis.append(now_p)
        cnt+=1
        if cnt==nokori:
            break

    return max(p_lis)
for i in range(n):
    p_lis=[]

    cnt=0
    now_p=0
    nxt=p[i]-1

    visited=set()

    while True:
        now_p+=c[nxt]
        nxt=p[nxt]-1
        p_lis.append(now_p)

        cnt+=1
        if cnt==k:
            break

        if k>300 and nxt in visited:
#            print(visited)
            break
        visited.add(nxt)

    if cnt!=k: # loop detected
#        print(i,p_lis)
        nokori = k-cnt
        loop_score=get_loop_score(nxt)
        if loop_score <= 0: # no loop
            nokori=len(visited)
        else: # loop as much as possible
            loops = nokori//len(visited) - 1
            now_p+= loops*loop_score
            nokori = loops*len(visited)

#        print("loop score:",loop_score)
        score = simulate(nxt,nokori)
        p_lis.append(score)

#    print(i,max(p_lis))

    ans=max(ans,max(p_lis))

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**13)
for cc in CC:
    cca = list(accumulate(cc))
    sc = sum(cc)
    if sc <= 0:
        # 1周分のうちの最大値
        if k < len(cc):
            ans = max(ans, max(cca[:k]))
        else:
            ans = max(ans, max(cca))
    else:
        # kk周したほうが良い
        kk, r = divmod(k, len(cc))
        if r == 0:
            ans = max(ans, kk*sc)
        else:
            ans = max(ans, kk*sc + max(cca[:r]))
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
maximum = -10**9
for i in range(n):
    totalfull = 0; totalcut = 0; count = 0; location = i
    maximumfull = -10**9; maximumcut = -10**9
    for j in range(min(n, k)):
        location = p[location]-1
        totalfull += c[location]
        maximumfull = max(maximumfull, totalfull)
        count += 1
        if location == i: break
    for j in range(k%count):
        location = p[location]-1
        totalcut += c[location]
        maximumcut = max(maximumcut, totalcut)
    maximum = max(maximum, max(maximumfull, k//count*totalfull+maximumcut))
print(maximum)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate

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

LOOP=[]
checked=[False]*N
tmp=[0]
NEXT=P[0]-1
checked[0]=True
while False in checked:
    if checked[NEXT]:
        LOOP.append(tmp)
        tmp=[]
        NEXT=checked.index(False)
    else:
        tmp.append(NEXT)
        checked[NEXT]=True
        NEXT=P[NEXT]-1
LOOP.append(tmp)

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

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = list(map(lambda x: int(x)-1, input().split()))
C = list(map(int, input().split()))
# print(C)
ans = -float("inf")
hoge = K
for i in range(N):
    K = hoge
    start_point = i
    visited = set()
    ruisekiwa = [0]
    tmp = 0
    for j in range(min(K, N)):
        # とりあえず回数の許す限り次のマスへ行く
        # ループしているなら
        if start_point in visited:
            break
        visited.add(start_point)
        ruisekiwa.append(ruisekiwa[-1]+C[P[start_point]])
        start_point = P[start_point]
    # ループが可能な場合
    if K > len(visited):
        # 可能な限りループする（最後の1回はループしない）
        tmp += ruisekiwa[-1]*(K//len(visited)-1)
        K %= len(visited)  # 余ったループ回数
        # 左側はもう1ループして，余力のループを行った場合．
        # 右側は最後の1ループを理想的なところで止めた場合
        # print("K %= N のあとの : ", K)
        if K != 0:
            tmp += max(ruisekiwa[-1]+max(ruisekiwa[1:K+1]), max(ruisekiwa[1:]))
        else:
            tmp += max(ruisekiwa)
        ans = max(ans, tmp)
    else:
        ans = max(ans, max(ruisekiwa[1:]))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
res = [0] * N
for i in range(N):
  x = i
  score = -float("inf")
  loopscore = 0
  loop = 0
  while x != i or loop == 0:
    loop += 1
    x = p[x] - 1
    loopscore += c[x]
    if loop <= K: score = max(score, loopscore)
  #print(loopscore)
  if loopscore <= 0:
    res[i] = score
  else:
    res[i] = K // loop * loopscore
    #print(res, loop, loopscore)
    plus = 0
    plusmx = 0
    x = i
    t = 0
    while t < K % loop:
      t += 1
      x = p[x] - 1
      plus += c[x]
      plusmx = max(plusmx, plus)
    res[i] += plusmx

print(max(res))

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = list(map(int,input().split()))
for i in range(n):
    p[i]-=1
c = list(map(int,input().split()))
par = [-1 for i in range(n)]
deep = [1 for i in range(n)]
ma = max(c)
def find(x):
    if par[x] < 0:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
def unite(x,y):
    x = find(x)
    y = find(y)
    if x == y:
        return False
    else:
        if deep[x] > deep[y]:
            par[x] += par[y]
            par[y] = x
        elif deep[x] < deep[y]:
            par[y] += par[x]
            par[x] = y
        else:
            par[x] += par[y]
            par[y] = x
            deep[x] += 1
        return True
def same(x,y):
    return find(x) == find(y)
def size(x):
    return -par[find(x)]
for i in range(n):
    unite(i,p[i])
for i in range(n):
    if par[i] >= 0:
        continue
    else:
        t = -par[i]
        if t >= k:
            for j in range(k):
                tmp = 0
                tmp2 = p[i]
                for l in range(j+1):
                    tmp += c[tmp2]
                    tmp2 = p[tmp2]
                tmp3 = p[i]
                ma = max(ma,tmp)
                for l in range(t):
                    tmp += c[tmp2]
                    tmp -= c[tmp3]
                    tmp2 = p[tmp2]
                    tmp3 = p[tmp3]
                    ma = max(ma,tmp)
        else:
            tmpp = p[i]
            tmp7 = 0
            for j in range(t):
                tmp7 += c[tmpp]
                tmpp = p[tmpp]
            if tmp7 <= 0:
                for j in range(t):
                    tmp = 0
                    tmp2 = p[i]
                    for l in range(j+1):
                        tmp += c[tmp2]
                        tmp2 = p[tmp2]
                    tmp3 = p[i]
                    ma = max(ma,tmp)
                    for l in range(t):
                        tmp += c[tmp2]
                        tmp -= c[tmp3]
                        tmp2 = p[tmp2]
                        tmp3 = p[tmp3]
                    ma = max(ma,tmp)
            else:
                g = k//t
                g2 = k//t - 1
                ma2 = 0
                ma3 = 0
                for j in range(k % t):
                    tmp = 0
                    tmp2 = p[i]
                    for l in range(j+1):
                        tmp += c[tmp2]
                        tmp2 = p[tmp2]
                    tmp3 = p[i]
                    ma2 = max(ma2,tmp)
                    for l in range(t):
                        tmp += c[tmp2]
                        tmp -= c[tmp3]
                        tmp2 = p[tmp2]
                        tmp3 = p[tmp3]
                        ma2 = max(ma2,tmp)
                ma2 += tmp7 * g
                for j in range(t):
                    tmp = 0
                    tmp2 = p[i]
                    for l in range(j+1):
                        tmp += c[tmp2]
                        tmp2 = p[tmp2]
                    tmp3 = p[i]
                    ma3 = max(ma3,tmp)
                    for l in range(t):
                        tmp += c[tmp2]
                        tmp -= c[tmp3]
                        tmp2 = p[tmp2]
                        tmp3 = p[tmp3]
                        ma3 = max(ma3,tmp)
                ma3 += tmp7 * g2
                ma = max(max(ma,ma2),ma3)
print(ma)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
C=[0]+list(map(int,input().split()))
P=[0]+list(map(int,input().split()))
D=[0 for i in range(N+1)]
D[0]=2
ANS=-10**20
for z in range(1,N+1):
    if D[z]==0:
        D[z]=1
        X=[[0,z]]
        for i in range(N*2):
            if D[X[-1][1]]!=3:
                D[X[-1][1]]+=1
                X.append([X[-1][0]+P[C[X[-1][1]]],C[X[-1][1]]])
            else:
                break
        #print(X)
        roop=(len(X)-1)//2
        
        Roop=max(0,X[roop][0])
        #print(roop)
        k=K%roop
        f=0
        if k==0:
            f=1
            k=roop
        cnt=0
        for i in range(1,k+1):
            for j in range(roop):
                #print(i+j,j)
                cnt=max(cnt,X[i+j][0]-X[j][0])
                #print(cnt)
        #print(cnt)
        ANS=max(ANS,(K//roop)*(Roop-f)+cnt)
if max(P[1:])<0:
    print(max(P[1:]))
else:
    print(ANS)

Submission status: Wrong Answer

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

co = 0
L = 0
s = 0
mod = 0
max = 0
for i in range(1,n+1):
	m = i
	while co == 0:
		s += c[m-1]
		m = p[m-1]
		L += 1
		if m == i:
			co += 1
	m = i
	for _ in range(k%L):
		mod += c[m-1]
		m = p[m-1]
	if (k//L)*s + mod >= max:
		max = (k//L)*s + mod
	co = 0
	L = 0
	s = 0
	mod = 0

print(max)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
P = list(map(int,input().split()))
C = list(map(int,input().split()))
ans = -10**100
for i in range(n):
    start = i
    cur = i
    i_s_score = 0
    i_s_score_max = C[P[cur]-1]
    move_num = 0
    for j in range(n):
        cur = P[cur]-1
        i_s_score += C[cur]
        i_s_score_max = max(i_s_score, i_s_score_max)
        move_num += 1
        if cur == start:
            break
    if i_s_score <= 0:
        ans = max(ans, i_s_score_max)
    else:
        ans = max(ans, i_s_score_max)
        temp = i_s_score*(k//move_num)
        temp_dash = i_s_score*(k//move_num-1)+i_s_score_max
        ans = max(ans, temp_dash)
        rest = k%move_num
        ans = max(ans, temp)
        i_s_score = temp
        for j in range(rest):
            cur = P[cur]-1
            i_s_score += C[cur]
            ans = max(ans, i_s_score)
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()))

check = [False] * (N+10)
roop = []

for i in range(1, N+1):
    tmp = []
    s = P[i-1]
    while True:
        if check[s]:
            break
        check[s] = True
        tmp.append(s)
        s = P[s-1]
    if len(tmp) > 0:
        roop.append(tmp)

ans = -10**18
for li in roop:
    SUM = 0
    for i in li:
        SUM += C[i-1]
    length = len(li)
    try_roop = K//length
    amari = K%length
    for j in range(length):
        tmp = -10**18
        if amari == 0:
            try_a = length - 1
        else:
            try_a = amari
        s = li[j]
        tmp1 = 0
        for k in range(try_a):
            tmp1 += C[s-1]
            tmp = max(tmp, tmp1)
            s = P[s-1]
        
        if SUM >= 0:
            ans = max(ans, SUM*try_roop + tmp)
        elif try_roop >= 1:
            ans = max(ans, SUM, tmp)
        else:
            ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
n, k = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
# n, k = 1000, 5000
# p = [random.randint(1, n) for _ in range(n)]
# c = [random.randint(-10000, 10000) for _ in range(n)]

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

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

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

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

Submission status: Wrong Answer

Solution code:
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

ans = -1 * 2 ** 30

if K <= N:
    for i in range(N):
        pos = i
        score = 0
        for j in range(K):
            score += C[pos]
            pos = P[pos]
            ans = max(ans, score)
    print(ans)
    exit(0)

for i in range(N):
    pos = i
    k = 0
    score = 0

    for j in range(N):
        score += C[pos]
        pos = P[pos]
        ans = max(ans, score)
        k += 1
        if pos == i:
            break

    score *= K // k
    ans = max(ans, score)
    for j in range(K % k):
        score += C[pos]
        pos = P[pos]
        ans = max(ans, score)
print(ans)

Submission status: Wrong Answer

Solution code:
def my_index(l, x, default=-1):
    if x in l:
        return l.index(x)
    else:
        return default

def my_int(s):
    return int(s)-1

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

dp = [False]*N

graph = []
i = 0
while(i != -1):
    
    init = i
    route = []
    while(True):
        dp[i] = True
        route.append(i)
        i = P[i]
        if (i == init):
            break
    
    graph.append(route)
    i = my_index(dp, False)

ans = -float('inf')

for g in range(len(graph)):
    d = len(graph[g])
    
    scores = [C[graph[g][i]] for i in range(d)]
    scores_loop = scores*2
    
    score = 0

    r = ((K-1) % d)+1
    
    for i in range(len(scores_loop)//2):
        for j in range(1,r+1):
            score = sum(scores_loop[i:i+j])
            if score > ans:
                ans = score
    
    summation = sum(scores)
    if summation > 0:
        if K > d:
            ans += summation*(K//d)
    
print(ans)

Submission status: Wrong Answer

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


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

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

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

score = 0
if K > N:
    sho = K // N
    yo = K % N
    K = yo
    if sum(C) > 0:
        score += sho * sum(C)

l = []
now = 0
for i in range(2 * N):
    now = P[now] - 1
    l.append(C[now])

m = -10 ** 9
for k in range(K):
    for n in range(N):
        m = max(sum(l[n: n + k + 1]), m)

print(score + m)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
x=0
A=[]
B=[0]*n
for i in range(n):
  X=[]
  x=i
  while B[x]==0:
    X.append(C[P[x]-1])
    B[x]=1
    x=P[x]-1
  if X!=[]:
    A.append(X)
m=M=max(C)
for a in A:
  l=len(a)
  S=sum(a)
  a=a+a
  for i in range(l):
    s=0
    for j in range(min(k,l)):
      s+=a[i+j]
      if j<k%l:
        m=max(m,s)
      else:
        M=max(M,m,s)
  m=max(m,m+S*(k//l),M,M+S*max(k//l-1,0))
print(m)