Problem Description
You are given an array receiver of length n and an integer k. There are n players (indexed from 0 to n−1) taking part in a ball-passing game. You choose a starting player i and then perform k passes such that the ball moves from player i to receiver[i], then to receiver[receiver[i]], and so on. The score of the game is the sum of the indices of all players who touched the ball (including repetitions and the starting player). The goal is to find the maximum possible score that can be achieved by choosing an optimal starting player.
Key Insights
- The passing sequence is defined by the receiver array, forming a directed graph with outdegree 1. Every sequence eventually falls into a cycle.
- Because k can be very large (up to 1e10), a simulation of k passes is not possible; instead, use a doubling technique (binary lifting) to "jump" many passes at once.
- Precompute, for each node (player) and for powers-of-two number of passes, both the destination and the cumulative score.
- For each starting player, build the final result by decomposing k into powers of two and accumulating the sums, then take the maximum score among all starting players.
Space and Time Complexity
Time Complexity: O(n log k), where n is the number of players and log k is the number of binary lifting steps. Space Complexity: O(n log k) for storing the doubling table.
Solution
We use a binary lifting (doubling) approach. For each player i, we want to know:
- The player reached after making 2^j passes.
- The cumulative sum of indices encountered during these passes (excluding the starting player in the first table entry if we treat it consistently).
The idea is to build a table dp[j][i] where:
- dp[0][i] = (receiver[i], receiver[i]) for one pass.
- For j > 0, dp[j][i] is computed by combining dp[j-1][i] and dp[j-1] of the resulting node:
- next = dp[j-1][ dp[j-1][i].first ].first
- sum = dp[j-1][i].second + dp[j-1][ dp[j-1][i].first ].second
After building the table for all j up to log2(k), for each starting player i, we initialize the total score with i (since the starting player touches the ball) and then simulate the remaining k passes by checking every bit of k. For every set bit at position j, we update the current state and add the corresponding sum. Finally, we choose the maximum score over all starting players.