You are given an integer array receiver of length n and an integer k.
n players are playing a ball-passing game.
You choose the starting player, i. The game proceeds as follows: player i
passes the ball to player receiver[i], who then passes it to
receiver[receiver[i]], and so on, for k passes in total. The game’s score is the sum of the indices of the players who touched the ball, including repetitions, i.e. i + receiver[i] + receiver[receiver[i]] + ... + receiver(k)[i].
Input: receiver =[2,0,1], k =4Output: 6Explanation:
Starting with player `i = 2` the initial score is2:Pass | Sender Index | Receiver Index | Score
---|---|---|---1|2|1|32|1|0|33|0|2|54|2|1|6
Input: receiver =[1,1,1,2,3], k =3Output: 10Explanation:
Starting with player `i = 4` the initial score is4:Pass | Sender Index | Receiver Index | Score
---|---|---|---1|4|3|72|3|2|93|2|1|10
This problem is a variation of the k-th ancestor problem, where we want to simulate k steps efficiently. By precomputing where the ball will be after 2^j passes for each player, we can use binary lifting to quickly compute the total score for any starting player and any k.
classSolution {
fungetMaxFunctionValue(receiver: IntArray, k: Long): Long {
val n = receiver.size
val LOG = 41val jump = Array(n) { IntArray(LOG) }
val sum = Array(n) { LongArray(LOG) }
for (i in0 until n) {
jump[i][0] = receiver[i]
sum[i][0] = receiver[i].toLong()
}
for (j in1 until LOG) {
for (i in0 until n) {
jump[i][j] = jump[jump[i][j-1]][j-1]
sum[i][j] = sum[i][j-1] + sum[jump[i][j-1]][j-1]
}
}
var ans = 0Lfor (i in0 until n) {
var score = i.toLong()
var pos = i
var rem = k
for (j in LOG-1 downTo 0) {
if ((rem shr j) and 1L==1L) {
score += sum[pos][j]
pos = jump[pos][j]
}
}
ans = maxOf(ans, score)
}
return ans
}
}
classSolution:
defgetMaxFunctionValue(self, receiver: list[int], k: int) -> int:
n, LOG = len(receiver), 41 jump = [[0]*LOG for _ in range(n)]
s = [[0]*LOG for _ in range(n)]
for i in range(n):
jump[i][0] = receiver[i]
s[i][0] = receiver[i]
for j in range(1, LOG):
for i in range(n):
jump[i][j] = jump[jump[i][j-1]][j-1]
s[i][j] = s[i][j-1] + s[jump[i][j-1]][j-1]
ans =0for i in range(n):
score, pos, rem = i, i, k
for j in range(LOG-1, -1, -1):
if (rem >> j) &1:
score += s[pos][j]
pos = jump[pos][j]
ans = max(ans, score)
return ans