Problem:


Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.



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


Sample output:
8

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - float('inf')
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    if tmp[-1] < 0:
        ans = max(ans, max(tmp))
    else:
        v = (tmp[-1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)

Submission status: Wrong Answer

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

ans = -100_000_000_000
for i in range(N):
    n = 0
    socre_sum = 0
    now = i
    while True:
        n += 1
        socre_sum += C[now]
        now = P[now]
        if i == now:
            break
    score = 0
    now = i
    for j in range(1, n+1):
        score += C[now]
        now = P[now]
        if j > K:
            break
        ans = max(ans, score+max(0, socre_sum)*(K-j)//n)
print(ans)

Submission status: Wrong Answer

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

ans = -100_000_000_000
for i in range(N):
    n = 0
    socre_sum = 0
    now = i
    while True:
        n += 1
        socre_sum += C[now]
        now = P[now]
        if i == now:
            break
    score = 0
    now = i
    for j in range(1, n+1):
        now = P[now]
        score += C[now]
        if j > K:
            break
        ans = max(ans, score+max(0, socre_sum)*(K-j)//n)
print(ans)

Submission status: Wrong Answer

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

ans = -100_000_000_000
for i in range(N):
    n = 0
    socre_sum = 0
    now = i
    while True:
        n += 1
        now = P[now]
        socre_sum += C[now]
        if i == now:
            break
    score = 0
    now = i
    for j in range(1, min(n+1, K+1)):
        now = P[now]
        score += C[now]
        ans = max(ans, score+max(0, socre_sum)*(K-j)//n)
print(ans)

Submission status: Wrong Answer

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

ans = -100_000_000_000
for i in range(N):
    n = 0
    socre_sum = 0
    now = i
    while True:
        n += 1
        socre_sum += C[now]
        now = P[now]
        if i == now:
            break
    score = 0
    now = i
    for j in range(1, min(n+1, K+1)):
        score += C[now]
        ans = max(ans, score+max(0, socre_sum)*(K-j)//n)
        now = P[now]
print(ans)

Submission status: Wrong Answer

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

ans = -100_000_000_000
for i in range(N):
    n = 1
    cost_cusum = [C[i]]
    now = P[i]
    while i != now:
        n += 1
        cost_cusum.append(cost_cusum[-1] + C[now])
        now = P[now]
    for i, c in enumerate(cost_cusum[:K]):
        ans = max(ans, c+max(0, cost_cusum[-1])*(K-i-1)//n)
print(ans)

Submission status: Wrong Answer

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

def loop(s):
    value = 0
    done = set()
    while s not in done:
        done.add(s)
        s = P[s]
        value += C[s]
    return len(done), value

def f(s,K):
    ans = -10**18
    total = 0
    done = set()
    while s not in done:
        done.add(s)
        s = P[s]
        total += C[s]
        ans = max(ans,total)
        K -= 1

        if K==0:
            return ans

    lamb, value = loop(s)
    
    if value > 0:
        total += (K//lamb)*value
        ans = max(ans,total)
        K %= lamb
    else:
        K = min(K,lamb)

    while K > 0:
        s = P[s]
        total += C[s]
        ans = max(ans,total)
        K -= 1
    return ans

print(max([f(s,K) for s in range(N)]))

Submission status: Wrong Answer

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

ans = -100_000_000_000
for i in range(N):
    n = 1
    cost_cusum = [C[i]]
    now = P[i]
    while i != now:
        n += 1
        cost_cusum.append(cost_cusum[-1] + C[now])
        now = P[now]
    for i, c in enumerate(cost_cusum):
        ans = max(ans, c+max(0, cost_cusum[-1])*(K-i-1)//n)
print(ans)

Submission status: Wrong Answer

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

def loop(s):
    value = 0
    done = set()
    while s not in done:
        done.add(s)
        s = P[s]
        value += C[s]
    return len(done), value

def f(s,K):
    ans = -10**18
    total = 0
    done = set()
    while s not in done:
        done.add(s)
        s = P[s]
        total += C[s]
        ans = max(ans,total)
        K -= 1

        if K==0:
            return ans

    lamb, value = loop(s)
    if value > 0:
        total += (K//lamb)*value
        ans = max(ans,total)
        K %= lamb
    while K > 0:
        s = P[s]
        total += C[s]
        ans = max(ans,total)
        K -= 1
    return ans

print(max([f(s,K) for s in range(N)]))

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

ans = -100_000_000_000
for i in range(N):
    n = 1
    cost_cusum = [C[i]]
    now = P[i]
    while i != now:
        n += 1
        cost_cusum.append(cost_cusum[-1] + C[now])
        now = P[now]
    q, r = divmod(K, n)
    if r:
        ma = max(cost_cusum[:r])
        ans = max(ans, ma, ma+cost_cusum[-1]*q)
    idx = max(range(n), key=lambda i: cost_cusum[i])
    if idx+1 > r:
        q -= 1
    ans = max(ans, cost_cusum[idx], cost_cusum[idx]+cost_cusum[-1]*q)
    # print(cost_cusum)
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=0
for i in range(n):
  count=0
  start=i+1
  for j in range(k):
    count+=c[p[start-1]-1]
    start=p[start-1]
    ans=max(ans,count)
print(ans)

Submission status: Wrong Answer

Solution code:
import queue

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

visited = [False] * N
q = queue.Queue()
lists = list()

for i in range(N):
    q.put(dict(index=i, l=None))
    while not q.empty():
        d = q.get()
        if visited[d['index']]:
            continue
        visited[d['index']] = True
        l = d['l']
        if l is None:
            l = list()
            lists.append(l)
        l.append(C[d['index']])
        q.put(dict(index=P[d['index']], l=l))

maxv = -float('inf')

for l in lists:
    summ = sum(l)
    if summ > 0:
        score = summ * (K//len(l))
        rest = K % len(l)
        if rest == 0:
            maxv = max(maxv, score)
            continue
        for i in range(len(l)):
            v = 0
            for j in range(rest):
                v += l[i+j if i+j < len(l) else i+j-len(l)]
                maxv = max(maxv, score+v)
    else:
        for i in range(len(l)):
            v = 0
            for j in range(len(l)):
                v += l[i+j if i+j < len(l) else i+j-len(l)]
                maxv = max(maxv, v)
print(maxv)

Submission status: Wrong Answer

Solution code:
import queue

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

visited = [False] * N
q = queue.Queue()
lists = list()

for i in range(N):
    q.put(dict(index=i, l=None))
    while not q.empty():
        d = q.get()
        if visited[d['index']]:
            continue
        visited[d['index']] = True
        l = d['l']
        if l is None:
            l = list()
            lists.append(l)
        l.append(C[d['index']])
        q.put(dict(index=P[d['index']], l=l))

maxv = -float('inf')

for l in lists:
    summ = sum(l)
    if summ > 0:
        score = summ * (K//len(l))
        rest = K % len(l)
        for i in range(len(l)):
            v = 0
            for j in range(rest):
                v += l[i+j if i+j < len(l) else i+j-len(l)]
                maxv = max(maxv, score+v)
    else:
        for i in range(len(l)):
            v = 0
            for j in range(len(l)):
                v += l[i+j if i+j < len(l) else i+j-len(l)]
                maxv = max(maxv, v)
print(maxv)

Submission status: Wrong Answer

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

vis = [0 for i in range(n+1)]

res = -10000000000000000000000
for i in range(0,n):
	if vis[i] == 0:
		su = 0
		vis[i] = 1
		v = []
		v.append(C[i])
		su += C[i]
		x = P[i]
		while x != i:
			vis[x] = 1
			su += C[x]
			v.append(C[x])
			x = P[x]
		vs = len(v)
		for i in range(vs):
			umm = 0
			for j in range(vs-1):
				x = (i+j)%vs
				umm += v[x]
				steps = 1+(x-i+vs)%vs
				if k >= vs:
					if(su > 0):
						r = max((k-steps)//vs,0)
						res = max(res, r*su + umm)
					else:
						res = max(res,umm)
				else:
					if steps <= k:
						res = max(res,umm)


print(res)

Submission status: Wrong Answer

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

vis = [0 for i in range(n+1)]

res = -10000000000000000000000
for i in range(0,n):
	if vis[i] == 0:
		su = 0
		vis[i] = 1
		v = []
		v.append(C[i])
		su += C[i]
		x = P[i]
		while x != i:
			vis[x] = 1
			su += C[x]
			v.append(C[x])
			x = P[x]
		vs = len(v)
		for i in range(vs):
			umm = 0
			for j in range(vs-1):
				x = (i+j)%vs
				umm += v[x]
				steps = 1+(x-i+vs)%vs
				if(su > 0):
					r = max((k-steps)//vs,0)
					res = max(res, r*su + umm)
				else:
					res = max(res,umm)


print(res)

Submission status: Wrong Answer

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

vis = [0 for i in range(n+1)]

res = -10000000000000000000000
for i in range(0,n):
	if vis[i] == 0:
		vis[i] = 1
		v = []
		v.append(C[i])
		x = P[i]
		while x != i:
			vis[x] = 1
			v.append(C[x])
			x = P[x]
		v.sort(reverse = True)
		vs = len(v)
		su = 0
		if k<vs:
			for j in range(k):
				su += v[j]
		else:
			for j in range(vs):
				su += v[j]
			su *= (k//vs)
			for j in range((k%vs)):
				su += v[j]
		res = max(res,su)
print(res)

Submission status: Wrong Answer

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

vis = [0 for i in range(n+1)]

res = -1
for i in range(0,n):
	if vis[i] == 0:
		vis[i] = 1
		v = []
		v.append(C[i])
		x = P[i]
		while x != i:
			vis[x] = 1
			v.append(C[x])
			x = P[x]
		v.sort(reverse = True)
		vs = len(v)
		su = 0
		if k<vs:
			for j in range(k):
				su += v[j]
		else:
			for j in range(vs):
				su += v[j]
			su *= (k//vs)
			for j in range((k%vs)):
				su += v[j]
		res = max(res,su)
print(res)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**28)
VV = []
 
for i in range(n):
  if i not in VV:
    order = []
    prev_pos = i
    visited = []
    sub_best = 0
    order = []
    l = 0
 
    for jjj in range(n):
      order.append(arr[prev_pos])
      #sub_best = max(sub_best, sum(order))
      visited.append(prev_pos)
      VV.append(prev_pos)
      l += 1
 
      next_pos = jump[prev_pos] - 1
      prev_pos = next_pos
      if next_pos in visited:
        break
 
    if sum(order)<1:
      limit = min(k,l*2)
      ss = 0
    else:
      limit = (k % l) + l
      limit = min(k,limit)
      ss = sum(order) * ((k//l) - 1)
 
    sub_best += ss
   # print(limit)
    
    order = order + order + order
    
    for chuj in range(1,limit+1):
      kk = sum(order[0:0+chuj])
      best = max(best, sub_best + kk)
      for op in range(len(order)-chuj):
        kk -= order[op]
        kk += order[op+chuj]
        best = max(best, sub_best + kk)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**28)
VV = []

for i in range(n):
  if i not in VV:
    order = []
    prev_pos = i
    visited = []
    sub_best = 0
    order = []
    l = 0

    for jjj in range(n):
      order.append(arr[prev_pos])
      #sub_best = max(sub_best, sum(order))
      visited.append(prev_pos)
      VV.append(prev_pos)
      l += 1

      next_pos = jump[prev_pos] - 1
      prev_pos = next_pos
      if next_pos in visited:
        break

    if sum(order)<1:
      limit = min(k,l)
      ss = 0
    else:
      limit = k % l
      ss = sum(order) * (k//l)

    sub_best += ss
    
    order = order + order
    
    for op in range(len(order)):
      for chuj in range(1,limit+1):
        kk = sum(order[op:op+chuj])
        best = max(best, sub_best + kk)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**28)
VV = []

for i in range(n):
  if i not in VV:
    order = []
    prev_pos = i
    visited = []
    sub_best = 0
    order = []
    l = 0

    for jjj in range(n):
      order.append(arr[prev_pos])
      #sub_best = max(sub_best, sum(order))
      visited.append(prev_pos)
      VV.append(prev_pos)
      l += 1

      next_pos = jump[prev_pos] - 1
      prev_pos = next_pos
      if next_pos in visited:
        break

    if sum(order)<1:
      limit = min(k,l)
      ss = 0
    else:
      limit = k % l
      ss = sum(order) * (k//l)

    sub_best += ss
    
    order = order + order
    
    for op in range(n):
      for chuj in range(1,limit+1):
        kk = sum(order[op:op+chuj])
        best = max(best, sub_best + kk)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**28)
VV = []

for i in range(n):
  if i not in VV:
    order = []
    prev_pos = i
    visited = []
    sub_best = 0
    order = []
    l = 0

    for jjj in range(n):
      order.append(arr[prev_pos])
      #sub_best = max(sub_best, sum(order))
      visited.append(prev_pos)
      VV.append(prev_pos)
      l += 1

      next_pos = jump[prev_pos] - 1
      prev_pos = next_pos
      if next_pos in visited:
        break

    if sum(order)<1:
      limit = min(k,l)
      ss = 0
    else:
      limit = k % l
      ss = sum(order) * (k//l)

    sub_best += ss
    
    order = order + order
    
    for op in range(n):
      kk = sum(order[op:op+limit])
      best = max(best, sub_best + kk)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**28)
VV = []

for i in range(n):
  if i not in VV:
    order = []
    prev_pos = i
    visited = []
    sub_best = 0
    order = []
    l = 0

    for jjj in range(n):
      order.append(arr[prev_pos])
      #sub_best = max(sub_best, sum(order))
      visited.append(prev_pos)
      VV.append(i)
      l += 1

      next_pos = jump[prev_pos] - 1
      prev_pos = next_pos
      if next_pos in visited:
        break

    if sum(order)<1:
      limit = min(k,l)
      ss = 0
    else:
      limit = k % l
      ss = sum(order) * (k//l)

    sub_best += ss
    
    order = order + order
    
    for op in range(n):
      kk = sum(order[op:op+limit])
      best = max(best, sub_best + kk)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**28)

for i in range(n):
  order = []
  prev_pos = i
  visited = []

  for jjj in range(n):
    order.append(arr[prev_pos])
    visited.append(prev_pos)
    
    next_pos = jump[prev_pos] - 1
    prev_pos = next_pos
    if next_pos in visited:
      break

  l = len(order)

  if sum(order)<0:
    limit = min(k,l)
    ss = 0
  else:
    limit = k % l
    ss = sum(order) * (k//l)
  

  tmp = 0 
  
  for j in range(limit):
    tmp += order[j % l]
    best = max(best, tmp)
    best = max(best, tmp + ss)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**18)

for i in range(n):
  order = []
  prev_pos = i
  visited = []

  for jjj in range(n):
    order.append(arr[prev_pos])
    visited.append(prev_pos)
    
    next_pos = jump[prev_pos] - 1
    prev_pos = next_pos
    if next_pos in visited:
      break

  l = len(order)

  if sum(order)<1:
    limit = min(k,l)
    ss = 0
  else:
    limit = k % l
    ss = sum(order[:l]) * (k//l)
  
  order = order

  tmp = 0 
  
  for j in range(limit):
    tmp += order[j % l]
    best = max(best, tmp + ss)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**18)

for i in range(n):
  order = []
  prev_pos = i
  visited = []

  for jjj in range(n):
    order.append(arr[prev_pos])
    visited.append(prev_pos)
    
    next_pos = jump[prev_pos] - 1
    prev_pos = next_pos
    if next_pos in visited:
      break

  l = len(order)

  if sum(order)<0:
    limit = min(k,l)
    ss = 0
  else:
    limit = k % l
    ss = sum(order[:l]) * (k//l)
  
  order = order

  tmp = 0 
  
  for j in range(limit):
    tmp += order[j % l]
    best = max(best, tmp + ss)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**18)

for i in range(n):
  order = []
  prev_pos = i
  visited = []

  for jjj in range(2*n):
    order.append(arr[prev_pos])
    visited.append(prev_pos)
    
    next_pos = jump[prev_pos] - 1
    prev_pos = next_pos
    if next_pos in visited:
      break

  l = len(order)

  if sum(order)<0:
    limit = min(k,l)
    ss = 0
  else:
    limit = k % l
    ss = sum(order[:l]) * (k//l)
  
  order = order+order

  tmp = 0 
  
  for j in range(limit):
    tmp += order[j % l]
    best = max(best, tmp + ss)
      
print(best)

Submission status: Wrong Answer

Solution code:
n, k = list(map(int,input().split()))
jump = list(map(int,input().split()))
arr = list(map(int,input().split()))
best = - (10**18)

for i in range(n):
  order = []
  prev_pos = i
  visited = []

  for jjj in range(2*n):
    order.append(arr[prev_pos])
    visited.append(prev_pos)
    
    next_pos = jump[prev_pos] - 1
    prev_pos = next_pos
    if next_pos in visited:
      break

  l = len(order)

  if sum(order)<0:
    limit = min(k,l)
  else:
    limit = k % l
  
 # print(l)
  order = order+order

  tmp = 0
  ss = sum(order[:l]) * (k//l) 
  
  for j in range(limit):
    tmp += order[j % l]
    best = max(best, tmp + ss)
      
print(best)

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

if  n >= k:
    for i in range(n):
        score = 0
        z = p[i] - 1
        for j in range(k):
            score += c[z]
            z = p[z] - 1
            if ans <= score:
                ans = score

else:
    for i in range(n):
        row = 0
        z = p[i] - 1
        for j in range(n):
            row += 1
            if p[i] == p[z]:
                break
            z = p[z] - 1
    for i in range(n):
        x = k // row
        z = p[i] - 1
        tol = 0
        total = -10 * 10
        frag = []
        for j in range(row):
            tol += c[z]
            z = p[z] - 1
            if tol >= total:
                total = tol
            frag.append(tol)
        if total > 0:
            x = k // row
            w = k % row
            score = (tol * x) + frag[w - 1]
            if ans<= score:
                ans = score
            z = p[i] - 1
            for l in range(row-1):
                score -= c[z]
                z = p[z] - 1
                if ans <= score:
                    ans = score
        else:
            if ans <= total:
                ans = total
    
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = [int(x)-1 for x in input().split()]
c = [int(x) for x in input().split()]
searched = [1] * n
pairs = []
points = []
search_plan = []
each_point = []

for i in range(n):
  now = i
  pair = []
  point = []
  if searched[i]:
    for j in range(n):
      if searched[now]:
        pair.append(now)
        searched[now] = 0
        now = p[now]
        point.append(c[now])
    pairs.append(pair)
    points.append(point)
    
search_plan = [pairs[i][points[i].index(max(points[i]))] for i in range(len(pairs))]

for i in search_plan:
  now = i
  check = []
  max_point = c[p[now]]
  point = 0
  for j in range(k):
    if now in check:
      l = len(check)
      lastpoint = point * int(k/l)
      for e in range(k%l):
        now = p[now]
        lastpoint += c[now]
      each_point.append(lastpoint)
      for e in range(l):
        lastpoint -= c[now]
        now = p.index(now)
      break
    check.append(now)    
    now = p[now]
    point += c[now]
    if max_point < point:
      max_point = point
  
  each_point.append(max_point) 
print(max(each_point))

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = [int(x)-1 for x in input().split()]
c = [int(x) for x in input().split()]
searched = [1] * n
pairs = []
points = []
search_plan = []
each_point = []

for i in range(n):
  now = i
  pair = []
  point = []
  if searched[i]:
    for j in range(n):
      if searched[now]:
        pair.append(now)
        searched[now] = 0
        now = p[now]
        point.append(c[now])
    pairs.append(pair)
    points.append(point)
    
search_plan = [pairs[i][points[i].index(max(points[i]))] for i in range(len(pairs))]

for i in search_plan:
  now = i
  check = []
  max_point = c[p[now]]
  point = 0
  for j in range(k):
    if now in check:
      l = len(check)
      lastpoint = point * int(k/l)
      for e in range(k%l):
        now = p[now]
        lastpoint += c[now]
      each_point.append(lastpoint)
      for e in range(l):
        lastpoint -= c[now]
        now = p.index(now)
      break
    check.append(now)    
    now = p[now]
    point += c[now]
    if max_point < point:
      max_point = point
  
  each_point.append(max_point)
print(each_point)  
print(max(each_point))

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
p = [int(x)-1 for x in input().split()]
c = [int(x) for x in input().split()]
searched = [1] * n
pairs = []
points = []
search_plan = []
each_point = []

for i in range(n):
  now = i
  pair = []
  point = []
  if searched[i]:
    for j in range(n):
      if searched[now]:
        pair.append(now)
        searched[now] = 0
        now = p[now]
        point.append(c[now])
    pairs.append(pair)
    points.append(point)
    
search_plan = [pairs[i][points[i].index(max(points[i]))] for i in range(len(pairs))]

for i in search_plan:
  now = i
  check = []
  max_point = c[p[now]]
  point = 0
  for j in range(k):
    if now in check:
      l = len(check)
      lastpoint = point * int(k/l)
      for e in range(k%l):
        now = p[now]
        lastpoint += c[now]
      each_point.append(lastpoint)
      
      now = check.index(now)+1
      c1 = check[now:]
      c2 = check[:now]
      for e in reversed(c1):
        each_point.append(p[e])
      for e in reversed(c2):
        each_point.append(p[e])
      break
    check.append(now)    
    now = p[now]
    point += c[now]
    if max_point < point:
      max_point = point
  
  each_point.append(max_point)
  
print(max(each_point))

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(len(p)):
    p[i] -= 1

ans = -10**20

for i in range(N):
    #iはスタートポジション
    pos = i
    #移動先のマスにかかれたポイント
    point = []
    total = 0
    while True:
        pos = p[pos]
        point.append(c[pos])
        # totalは周期の和がマイナスかプラスかで後々場合分けするために使う。(周期が負だったら一巡目で終わらせたい。周期が正だったらできる限り後の方で終わらせたい)
        total += c[pos]
        #スタートポジションに戻ってきた==サイクルを検知した
        if pos == i: break
    l = len(point)

    t = 0
    #total<0のときはif total>0以外の処理でまきとれる
    for i in range(l):
        t += point[i]
        #Kがi+1より小さい時のハンドリング
        if i+1 > K: break
        now = t
        if total > 0:
            #K-i-1の-1はポイントの一個目を獲得する時に1個動くので-1。二こ目のポイントを取る時はi=1で、K-2になり計算が合う。それをlでわり周期が何個回れるかを計算する
            #nowはtotalのセットが何個かあって、その先にpoint[i]がくっつくイメージ。[a,b,c] + [a,b,c] + [a,b,c] + ([a] or [a+b] + [a+b+c]) 
            now += (total * (K-i-1)//l)
        ans = max(ans, now)
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(len(p)):
    p[i] -= 1

ans = float("-inf")

for i in range(N):
    #iはスタートポジション
    pos = i
    #移動先のマスにかかれたポイント
    point = []
    total = 0
    while True:
        pos = p[pos]
        point.append(c[pos])
        # totalは周期の和がマイナスかプラスかで後々場合分けするために使う。(周期が負だったら一巡目で終わらせたい。周期が正だったらできる限り後の方で終わらせたい)
        total += c[pos]
        #スタートポジションに戻ってきた==サイクルを検知した
        if pos == i: break
    l = len(point)

    t = 0
    #total<0のときはif total>0以外の処理でまきとれる
    for i in range(l):
        t += point[i]
        #Kがi+1より小さい時のハンドリング
        if i+1 > K: break
        now = t
        if total > 0:
            #K-i-1の-1はポイントの一個目を獲得する時に1個動くので-1。二こ目のポイントを取る時はi=1で、K-2になり計算が合う。それをlでわり周期が何個回れるかを計算する
            #nowはtotalのセットが何個かあって、その先にpoint[i]がくっつくイメージ。[a,b,c] + [a,b,c] + [a,b,c] + ([a] or [a+b] + [a+b+c]) 
            now += (total * (K-i-1)//l)
        ans = max(ans, now)
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(len(p)):
    p[i] -= 1

ans = float("-inf")

for i in range(N):
    #iはスタートポジション
    pos = i
    #移動先のマスにかかれたポイント
    point = []
    total = 0
    while True:
        pos = p[pos]
        point.append(c[pos])
        # totalは周期の和がマイナスかプラスかで後々場合分けするために使う。(周期が負だったら一巡目で終わらせたい。周期が正だったらできる限り後の方で終わらせたい)
        total += c[pos]
        #スタートポジションに戻ってきた==サイクルを検知した
        if pos == i: break
    l = len(point)

    t = 0
    #total<0のときはif total>0以外の処理でまきとれる
    for i in range(l):
        t += point[i]
        #Kがi+1より小さい時のハンドリング
        if i+1 > K: break
        now = t
        if total > 0:
            #K-i-1の-1はポイントの一個目を獲得する時に1個動くので-1。二こ目のポイントを取る時はi=1で、K-2になり計算が合う。それをlでわり周期が何個回れるかを計算する
            #nowはtotalのセットが何個かあって、その先にpoint[i]がくっつくイメージ。[a,b,c] + [a,b,c] + [a,b,c] + ([a] or [a+b] + [a+b+c]) 
            now += total * (K-i-1)//l
        ans = max(ans, now)
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(len(p)):
    p[i] -= 1

ans = float("-inf")

for i in range(N):
    #iはスタートポジション
    pos = i
    #移動先のマスにかかれたポイント
    point = []
    total = 0
    while True:
        pos = p[pos]
        point.append(c[pos])
        # totは周期の和がマイナスかプラスかで後々場合分けするために使う。(周期が負だったら一巡目で終わらせたい。周期が正だったらできる限り後の方で終わらせたい)
        total += c[pos]
        #スタートポジションに戻ってきた==サイクルを検知した
        if pos == i: break
    l = len(point)

    t = 0
    #total<0のときはif total>0以外の処理でまきとれる
    for i in range(l):
        t += point[i]
        #Kがi+1より小さい時のハンドリング
        if i+1 > K: break
        now = t
        if total > 0:
            #K-i-1の-1はポイントの一個目を獲得する時に1個動くので-1。二こ目のポイントを取る時はi=1で、K-2になり計算が合う。それをlでわり周期が何個回れるかを計算する
            #nowはtotalのセットが何個かあって、その先にpoint[i]がくっつくイメージ。[a,b,c] + [a,b,c] + [a,b,c] + ([a] or [a+b] + [a+b+c]) 
            now += total * (K-i-1)//l
        ans = max(ans, now)
print(ans)