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:
def D():
    N, K = map(int, input().split())
    P = [int(n) for n in input().split()]
    C = [int(n) for n in input().split()]
    cycle_sums = [float('-inf')]*N
    cycle_length = [-1]*N
    for i in range(N):
        # every element is guaranteed to be in a cycle
        if cycle_sums[i] == float('-inf'): #have not been processed, g
            points = 0
            visited_order = [i]
            while P[i] != i:
                visited_order.append(P[i])
                i = P[i]-1
            _sum = 0
            for j in range(len(visited_order)):
                _sum += C[visited_order[j]-1]
            for j in range(len(visited_order)):
                cycle_sums[visited_order[j]-1] = _sum
                cycle_length[visited_order[j]-1] = len(visited_order)
    #print(cycle_sums, cycle_length)

    ans = float('-inf')
    for j in range(N):
        i = j
        k = K
        points = 0
        if cycle_sums[i] > 0:
            num_cycles, remainder = divmod(k, cycle_length[i])
            if num_cycles > 0:
                num_cycles -= 1
                remainder += cycle_length[i]
            points += cycle_sums[i] * num_cycles
            k = remainder
        else:
            #make at least one move
            i = P[i]-1
            points += C[i]
            k = min(k, cycle_length[i]-1)
        #print(j, points)
        _sum = points

        while k > 0:
            i = P[i]-1
            _sum += C[i]
            points = max(points, _sum)
            k -= 1
        #print(j, points)
        ans = max(ans, points)

    return ans
        # visited_dict = {}
        # visited_order = []
        # while K > 0 and P[i] not in visited_dict:
        #     visited_dict[P[i]] = len(visited_order)
        #     visited_order.append(P[i])
        #     i = P[i]-1
        #     points += C[i]
        # if K > 0: #cycle found
        #     cycle_len = len(visited_order) - visited_dict(P[i])
        #     num_cycles_left, remainder = divmod(K, cycle_len)
        #     _sum = 0
        #     for j in range(visited_dict(P[i]), len(visited_order)):
        #         _sum += C[visited_order[j]]
        #         if j - visited_dict(P[i]) == remainder-1:
        #             points += _sum
        #     points += num_cycles_left*_sum

print(D())

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

INF = 10**18
score = -INF
for st in range(n):
    tot = 0 # cost of one lap
    costs = []
    nx = st
    while True:
        nx = P[nx]
        costs.append(C[nx])
        tot += C[nx]
        if nx == st: break

    lap_c = -INF # lap costs
    # r = k
    r = len(costs)
    if tot >= 0:
        nl, r = divmod(k, len(costs)) # number of loops
        if nl == 0: lap_c = -INF
        else: lap_c = tot * nl
        # print('nl {}, k {}'.format(nl, k))

    sum_c = 0
    max_c = -INF
    # for c in costs[:min(r, len(costs))]:
    for c in costs[:r]:
        sum_c += c
        max_c = max(max_c, sum_c)

    score = max(score, lap_c, max_c, lap_c + max_c)

    # print(st, costs, tot)
    # print(lap_c, max_c, lap_c+max_c, '=', score)

print(score)

# print('===')
# print(n,k)
# print(P)
# print(C,end='\n\n')

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

INF = 10**18
score = -INF
for st in range(n):
    tot = 0 # cost of one lap
    costs = []
    nx = st
    while True:
        nx = P[nx]
        costs.append(C[nx])
        tot += C[nx]
        if nx == st: break

    lap_c = -INF # lap costs
    r = k
    if tot >= 0:
        nl, r = divmod(k, len(costs)) # number of loops
        if nl == 0:
            lap_c = -INF
        else:
            lap_c = max(lap_c, tot * nl)
        # print('nl {}, k {}'.format(nl, k))

    sum_c = 0
    max_c = -INF
    for c in costs[:min(r, len(costs))]:
        sum_c += c
        max_c = max(max_c, sum_c)

    score = max(score, lap_c, max_c, lap_c + max_c)

    # print(st, costs, tot)
    # print(lap_c, max_c, lap_c+max_c, '=', score)

print(score)

# print('===')
# print(n,k)
# print(P)
# print(C,end='\n\n')

Submission status: Wrong Answer

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

a = [[] for i in range(n)]
ans = -1000000000

for i in range(n):
  x = i
  y = 0
  z = -1000000000
  cg = []
  while True:
    y += c[x]
    z = max(z, y)
    cg.append(y)
    x = p[x] - 1
    if x == i:
      break

  if y < 0:
    for j in range(k % len(cg)):
      ans = max(ans, cg[j])
  else:
    ka = k // len(cg)
    kb = k % len(cg)
    if kb == 0:
      ans = max(ans, (ka - 1) * y + z)
    else:
      for j in range(kb):
        ans = max(ans, ka * y + cg[j])
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

INF = 10**18
score = -INF
for st in range(n):
    tot = 0 # cost of one lap
    costs = []
    nx = st
    while True:
        nx = P[nx]
        costs.append(C[nx])
        tot += C[nx]
        if nx == st: break

    # print(st, tot, costs)

    lap_c = -INF # lap costs
    remain = len(costs) # number of costs
    if tot >= 0:
        nl, remain = divmod(k, remain) # number of loops, remain
        # print('nl {}, remain {}'.format(nl,remain))
        # lap_c = max(lap_c, tot * (nl))
        lap_c = max(lap_c, tot * (nl-1))

        # if remain == 0:
        #     lap_c = max(lap_c, tot * nl)
        # else:
        #     lap_c = max(lap_c, tot * (nl-1))
            # remain += len(costs)
    #     print('nl {}, remain {}, k {}'.format(nl,remain,k))
    # print('lap_c {}, remain {}'.format(lap_c,remain))

    # print('lap_c {}'.format(lap_c if lap_c!=-INF else '-'))

    sum_c = 0
    max_c = -INF
    for i in range(len(costs)+remain):
        j = (i + remain) % len(costs)
        c = costs[j]
        sum_c += c
        max_c = max(max_c, sum_c)

    tot_c = lap_c + max_c
    score = max(score, lap_c, max_c, tot_c)

    # print('max_c {}'.format(max_c if max_c!=-INF else '-'))
    # print('tot_c {}'.format(tot_c if lap_c!=-INF and max_c!=-INF else '-'))
    # print('score {}'.format(score))
    # print('---')


print(score)

# print('===')
# print(n,k)
# print(P)
# print(C,end='\n\n')

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int, input().split()))
c=list(map(int, input().split()))
def f(x,m):
  if m==0:return 0
  tmp=c[x]
  a=tmp
  x=p[x]-1
  for i in range(m-1):
    tmp+=c[x]
    a=max(a,tmp)
    x=p[x]-1
  return a
def F(x):
  tmp=c[x]
  m=p[x]-1
  i=1
  while m!=x:
    i+=1
    tmp+=c[m]
    m=p[m]-1
  return (tmp,i)
ans=-float("INF")
for i in range(n):
  s,z=F(i)
  if s>0:
    tmp=s*(k//z)+f(i,k%z)
  else:
    tmp=f(i,min(n,k))
  ans=max(ans, tmp)
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()))
s=sum(c)
def f(x,m):
  tmp=0
  a=-float("INF")
  for i in range(m):
    tmp+=c[x]
    a=max(a,tmp)
    x=p[x]-1
  return a
if s>0:
  ans=s*(k//n)
  tmp=-float("INF")
  for i in range(n):
    tmp=max(tmp, f(i,k%n))
  ans+=tmp
else:
  ans=-float("INF")
  for i in range(n):
    ans=max(ans, f(i,min(n,k)))
print(ans)

Submission status: Wrong Answer

Solution code:
def D():
    N, K = map(int, input().split())
    P = [int(n) for n in input().split()]
    C = [int(n) for n in input().split()]
    cycle_sums = [-float('inf')]*N
    cycle_length = [-1]*N
    for i in range(N):
        # every element is guaranteed to be in a cycle
        if cycle_sums[i] < 0: #have not been processed, g
            points = 0
            visited_set = set()
            visited_order = []
            while K > 0 and P[i] not in visited_set:
                visited_set.add(P[i])
                visited_order.append(P[i])
                i = P[i]-1
            _sum = 0
            for j in range(len(visited_order)):
                _sum += C[visited_order[j]-1]
            for j in range(len(visited_order)):
                cycle_sums[visited_order[j]-1] = _sum
                cycle_length[visited_order[j]-1] = len(visited_order)
    #print(cycle_sums, cycle_length)

    ans = float('-inf')
    for j in range(N):
        i = j
        k = K
        points = 0
        if cycle_sums[i] > 0:
            num_cycles, remainder = divmod(k, cycle_length[i])
            points += cycle_sums[i] * num_cycles
            k = remainder
            count = 0
        else:
            #make at least one move
            i = P[i]-1
            points += C[i]
            k -= 1
            count = 1

        #print(j, points)
        _sum = points

        while k > 0 and count < cycle_length[i]:
            i = P[i]-1
            _sum += C[i]
            points = max(points, _sum)
            count += 1
            k -= 1
        #print(j, points)
        ans = max(ans, points)

    return ans

print(D())

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=list(map(int, input().split()))
c=list(map(int, input().split()))
s=sum(c)
def f(x,m):
  tmp=0
  a=0
  for i in range(m):
    tmp+=c[x]
    a=max(a,tmp)
    x=p[x]-1
  return a
if s>0:
  ans=s*(k//n)
  tmp=0
  for i in range(n):
    tmp=max(tmp, f(i,k%n))
  ans+=tmp
else:
  ans=0
  for i in range(n):
    ans=max(ans, f(i,min(n,k)))
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

INF = 10**18
score = -INF
for st in range(n):
    tot = 0 # cost of one lap
    costs = []
    nx = st
    while True:
        nx = P[nx]
        costs.append(C[nx])
        tot += C[nx]
        if nx == st: break

    lap_c = -INF # lap costs
    r = k
    if tot >= 0:
        nl, r = divmod(k, len(costs)) # number of loops
        lap_c = max(lap_c, tot * nl)
        # print('nl {}, k {}'.format(nl, k))

    sum_c = 0
    max_c = -INF
    for c in costs[:min(r, len(costs))]:
        sum_c += c
        max_c = max(max_c, sum_c)

    score = max(score, lap_c, max_c, lap_c + max_c)

    # print(st, costs, tot)
    # print(lap_c, max_c, lap_c+max_c, '=', score)

print(score)

# print('===')
# print(n,k)
# print(P)
# print(C,end='\n\n')

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18
for saisyo in range(1,n+1):
    nokoriidoukaisuu=k
    tensuu=0
    tensuulist=[]
    genzaiti=saisyo

    while(True):
        genzaiti=p[genzaiti]
        nokoriidoukaisuu-=1
        tensuu+=c[genzaiti]
        tensuulist.append(c[genzaiti])
        ans=max(ans,tensuu)
        if genzaiti==saisyo:
            break
        if nokoriidoukaisuu==0:
            break

    if sum(tensuulist)<=0:
        continue
    else:
        syuki=len(tensuulist)
        tensuu+=(nokoriidoukaisuu//syuki)*sum(tensuulist)
        nokoriidoukaisuu-=(nokoriidoukaisuu//syuki)*syuki
        ans=max(ans,tensuu)
        for i in range(nokoriidoukaisuu):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18
for saisyo in range(1,n+1):
    nokoriidoukaisuu=k
    tensuu=0
    tensuulist=[]
    genzaiti=saisyo

    while(True):
        genzaiti=p[genzaiti]
        nokoriidoukaisuu-=1
        tensuu+=c[genzaiti]
        tensuulist.append(c[genzaiti])
        ans=max(ans,tensuu)
        if genzaiti==saisyo:
            break
        if nokoriidoukaisuu==0:
            break

    if sum(tensuulist)<=0:
        continue
    else:
        syuki=len(tensuulist)
        tensuu+=(nokoriidoukaisuu//syuki)*sum(tensuulist)
        nokoriidoukaisuu-=(nokoriidoukaisuu//syuki)*syuki
        for i in range(nokoriidoukaisuu):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)

print(ans)

Submission status: Wrong Answer

Solution code:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())

def resolve():
    N, K = iim()
    P = list(i-1 for i in iim())
    C = list(iim())

    inf = float("inf")
    vis = [0] * N
    dp = [0]* N
    aa = []
    for n in range(N):
        if vis[n]:
            continue
        pos = n
        dp = []
        while True:
            if vis[pos]:
                break
            vis[pos] = True
            pos = P[pos]
            dp.append(C[pos])
        aa.append(dp)

    def calc(a, k):
        n = len(a)

        def f(n):
            if n == 1:
                return max(a)

            dp = [0] * n
            ans = -inf
            for i in range(-n+1, n):
                ai = a[i]
                for j in range(n):
                    dp[j] += ai
                for j in range(min(i+n-1, n)):
                    dp[j] -= a[i-j-1]

                ans = max(ans, *dp)
            return ans

        if n < k:
            sm = sum(a)
            if sm > 0:
                i, n = divmod(k, n)
                sm *= i

                if n == 0:
                    return max(f(len(a)), sm)
            else:
                sm = 0
        else:
            sm = 0

        return f(n) + sm

    ans = -inf
    for a in aa:
        ans = max(ans, calc(a, K))
    print(ans)

if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

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

for i in range(N):
    start = i
    now = P[i] -1
    score = C[now]
    step = 1
    if answer < score:
        answer = score
    while start != now and step < K:
        now = P[now] -1
        score += C[now]
        step += 1
        if answer < score:
            answer = score
    score *= (K // step)
    for j in range(K % step):
        now = P[now] -1
        score += C[now]
        if answer < score:
            answer = score

print(answer)

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**18
for start in range(N):
    now = start
    cycle = [0]

    while True:
        now = P[now] - 1
        cycle.append(cycle[-1] + C[now])

        if now == start: break

    L = len(cycle)-1
    if cycle[-1] < 0 or K <= L:
        score = max(cycle[1:min(L+1,K)+1])
    else:
        score = cycle[-1]*(K//L) + max(cycle[:K%L+1])
        
    ans = max(ans, 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()))
loop_flags = [False] * N
loops = []
for i in range(N):
    if loop_flags[i]:
        continue
    next_cell = i
    loop = []
    while not loop_flags[next_cell]:
        loop_flags[next_cell] = True
        loop.append(C[next_cell])
        next_cell = P[next_cell] - 1
    if loop:
        loops.append(loop)
# print(loops)

ans = -float('inf')
for loop in loops:
    sum_score = sum(loop)
    if sum_score > 0:
        if K % len(loop) == 0:
            sum_val = sum_score * (K // len(loop) - 1)
            now_K = 1
        else:
            sum_val = sum_score * (K // len(loop))
            now_K = K % len(loop)
    else:
        sum_val = 0
        now_K = min(len(loop), K)
    for i in range(1, now_K + 1):
        target = sum_val
        target += sum(loop[:i])
        ans = max(target, ans)
        for j in range(len(loop)):
            target = target - loop[j] + loop[(i + j) % len(loop)]
            ans = max(target, ans)
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**18
for start in range(N):
    now = start
    cycle = [0]

    while True:
        now = P[now] - 1
        cycle.append(cycle[-1] + C[now])

        if now == start: break

    L = len(cycle)-1
    if cycle[-1] < 0 or K <= L:
        score = max(cycle[1:min(L+1,K+1)+1])
    else:
        score = cycle[-1]*(K//L) + max(cycle[:K%L+1])

    ans = max(ans, 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()))
ans=-10**18
flag=dict()
for i in range(n):
    if i in flag:
        continue
    cur=i
    accum=[]
    flag[cur]=0
    s=0
    while flag[cur]<2:
        cur=p[cur]-1
        s+=c[cur]
        accum.append(s)
        if cur not in flag:
            flag[cur]=0
        else:
            flag[cur]+=1
    l=len(accum)//2
    accum=[0]+accum
    #print(accum)
    for x in range(1,l+1):
        if accum[x+l-1]-accum[x-1]<=0 or k//l<1:
            ans=max(ans,max(accum[x:x+min(k,l)])-accum[x-1])
        else:
            a=max(accum[x:x+l-1])-accum[x-1]
            if k%l!=0:
                b=max(accum[x:x+k%l])-accum[x-1]
            else:
                b=max(accum[x:x+l-1])-accum[x-1]
            d=accum[x+l-1]-accum[x-1]
            ans=max(ans,max(k//l*d,k//l*d+b,(k//l-1)*d+a))
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**18
flag=dict()
for i in range(n):
    if i in flag:
        continue
    cur=i
    accum=[]
    flag[cur]=0
    s=0
    while flag[cur]<2:
        cur=p[cur]-1
        s+=c[cur]
        accum.append(s)
        if cur not in flag:
            flag[cur]=0
        else:
            flag[cur]+=1
    l=len(accum)//2
    accum=[0]+accum
    #print(accum)
    for x in range(1,l+1):
        if accum[x+l-1]-accum[x-1]<=0:
            ans=max(ans,max(accum[x:x+min(k,l)])-accum[x-1])
        else:
            a=max(accum[x:x+l-1])-accum[x-1]
            if k%l!=0:
                b=max(accum[x:x+k%l])-accum[x-1]
            else:
                b=max(accum[x:x+l-1])-accum[x-1]
            d=accum[x+l-1]-accum[x-1]
            ans=max(ans,max(k//l*d,k//l*d+b,max(k//l-1,0)*d+a))
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18
for saisyo in range(1,n+1):
    nokoriidoukaisuu=k
    tensuu=0
    tensuulist=[]
    genzaiti=p[saisyo]
    
    while(True):
        tensuu+=c[genzaiti]
        tensuulist.append(c[genzaiti])
        genzaiti=p[genzaiti]
        nokoriidoukaisuu-=1
        ans=max(ans,tensuu)
        if nokoriidoukaisuu==0:
            break
        if genzaiti==saisyo:
            tensuu+=c[genzaiti]
            tensuulist.append(c[genzaiti])
            genzaiti=p[genzaiti]
            nokoriidoukaisuu-=1
            ans=max(ans,tensuu)
            break

    if sum(tensuulist)<=0:
        continue
    else:
        syuki=len(tensuulist)
        tensuu+=(nokoriidoukaisuu//syuki)*sum(tensuulist)
        nokoriidoukaisuu-=(nokoriidoukaisuu//syuki)*syuki
        for i in range(nokoriidoukaisuu):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18
for saisyo in range(1,n+1):
    nokoriidoukaisuu=k
    tensuu=0
    tensuulist=[]
    genzaiti=p[saisyo]
    
    while(True):
        tensuu+=c[genzaiti]
        tensuulist.append(c[genzaiti])
        genzaiti=p[genzaiti]
        nokoriidoukaisuu-=1
        ans=max(ans,tensuu)
        if nokoriidoukaisuu==0:
            break
        if genzaiti==saisyo:
            tensuu+=c[genzaiti]
            tensuulist.append(c[genzaiti])
            genzaiti=p[genzaiti]
            nokoriidoukaisuu-=1
            ans=max(ans,tensuu)
            break

    if sum(tensuulist)<0:
        continue
    else:
        syuki=len(tensuulist)
        tensuu+=(nokoriidoukaisuu//syuki)*sum(tensuulist)
        nokoriidoukaisuu%=syuki
        for i in range(nokoriidoukaisuu):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18
for saisyo in range(1,n+1):
    nokoriidoukaisuu=k
    tensuu=0
    tensuulist=[]
    genzaiti=p[saisyo]
    
    while(True):
        tensuu+=c[genzaiti]
        tensuulist.append(c[genzaiti])
        genzaiti=p[genzaiti]
        nokoriidoukaisuu-=1
        ans=max(ans,tensuu)
        if nokoriidoukaisuu==0:
            break
        if genzaiti==saisyo:
            tensuu+=c[genzaiti]
            tensuulist.append(c[genzaiti])
            genzaiti=p[genzaiti]
            nokoriidoukaisuu-=1
            ans=max(ans,tensuu)
            break

    if sum(tensuulist)<=0:
        continue
    else:
        syuki=len(tensuulist)
        tensuu+=(nokoriidoukaisuu//syuki)*sum(tensuulist)
        nokoriidoukaisuu%=syuki
        for i in range(nokoriidoukaisuu):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
p=[int(x) for x in input().rstrip().split()]
c=[int(x) for x in input().rstrip().split()]

ind=0
ans=-float('inf')
for i in range(n):

  now_l=[] 
  prev=i
  now=0
  ma=-float('inf')
  
  for j in range(n):
    if p[prev] not in now_l:
      now+=c[p[prev]-1]
      now_l.append(p[prev])
      ma=max(now,ma)

    else:
      break
    prev=p[prev]-1
  # print(now)
  if now < 0:
    ans=max(ans,ma)
  else:
    num=k//len(now_l)
    ans=max(ans,ma*num+now*num)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18
for saisyo in range(1,n+1):
    genzaiti=p[saisyo]
    nokoriidoukaisuu=k
    tensuu=0
    tensuulist=[]

    while(True):
        tensuu+=c[genzaiti]
        genzaiti=p[genzaiti]
        nokoriidoukaisuu-=1
        ans=max(ans,tensuu)
        tensuulist.append(c[genzaiti])
        if nokoriidoukaisuu==0:
            break
        if genzaiti==saisyo:
            tensuu+=c[genzaiti]
            genzaiti=p[genzaiti]
            nokoriidoukaisuu-=1
            ans=max(ans,tensuu)
            tensuulist.append(c[genzaiti])
            break

    if sum(tensuulist)<=0:
        continue
    else:
        syuki=len(tensuulist)
        tensuu+=(nokoriidoukaisuu//syuki)*sum(tensuulist)
        nokoriidoukaisuu%=syuki
        for i in range(nokoriidoukaisuu):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)

print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
p = [0]+[int(x) for x in input().split()]
c = [0]+[int(x) for x in input().split()]

ans=-10**18
for saisyo in range(1,n+1):
    genzaiti=p[saisyo]
    nokoriidoukaisuu=k
    tensuu=0
    tensuulist=[]

    while(True):
        tensuu+=c[genzaiti]
        genzaiti=p[genzaiti]
        nokoriidoukaisuu-=1
        ans=max(ans,tensuu)
        tensuulist.append(c[p[genzaiti]])
        if nokoriidoukaisuu==0:
            break
        if genzaiti==saisyo:
            tensuu+=c[genzaiti]
            genzaiti=p[genzaiti]
            nokoriidoukaisuu-=1
            ans=max(ans,tensuu)
            tensuulist.append(c[p[genzaiti]])
            break

    if sum(tensuulist)<=0:
        continue
    else:
        syuki=len(tensuulist)
        tensuu+=(nokoriidoukaisuu//syuki)*sum(tensuulist)
        nokoriidoukaisuu%=syuki
        for i in range(nokoriidoukaisuu):
            tensuu+=tensuulist[i]
            ans=max(ans,tensuu)

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 (0, N):
    P[i] = P[i]-1

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

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

D = list(uf.all_group_members().values())

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 (0, N):
    P[i] = P[i]-1
 
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())
 
uf = UnionFind(N)
 
for i in range (0, N):
    uf.union(i, P[i])
 
D = list(uf.all_group_members().values())
A = [0]*N
 
for i in range (0, len(D)):
    V = D[i]
    sV = 0
    for l in range (0, len(V)):
        sV+=C[V[l]]
        if sV >= 0:
            for j in range (0, len(V)):
                V = D[i]
                W = V[j:N]+V[0:j]
                if K%len(V)> 0:
                    extramatrix = [0]*(K%len(V))
                    for k in range (0, K%len(V)):
                        extramatrix[k]=C[W[k]]
                    for k in range (1, K%len(V)):
                        extramatrix[k]+= extramatrix[k-1]
                    extra = max(extramatrix)
                else:
                    extra = 0
                A[V[j]] = sV*(K//len(V))+extra
        else:
            for j in range (0, len(V)):
                V = D[i]
                W = V[j:N]+V[0:j]
                if K%len(V)> 0:
                    extramatrix = [0]*(K%len(V))
                    for k in range (0, K%len(V)):
                        extramatrix[k]=C[W[k]]
                    for k in range (1, K%len(V)):
                        extramatrix[k]+= extramatrix[k-1]
                    extra = max(extramatrix)
                else:
                    extramatrix = [0]*(len(V))
                    for k in range (0, len(V)):
                        extramatrix[k]=C[W[k]]
                    for k in range (1, len(V)):
                        extramatrix[k]+= extramatrix[k-1]
                    extra = max(extramatrix)
                A[V[j]] = extra

print(max(A))