![]() |
VOOZH | about |
Given an undirected graph of V nodes and E edges and an array coins[] of size V, such that coins[i] = number of coins present at ith node. Initially, choose any node uniformly at random and pick all the coins available on that node. In one move, we can move from the current node to any of its neighboring nodes. The task is to find the expected number of coins we can collect after K moves. Return the answer mod 109+7.
Note: 0-Based Indexing is followed in array i.e. coins[0] denotes the number of coins at node 1.
Examples:
Input: V = 4, E = 4, K = 1, edges[][] = {{0, 1}, {1, 2}, {2, 0}, {2, 3}}, coins[] = {1, 1, 1, 2}
Output: 333333338
Explanation:
- If we start from node 0, then we will get 1 coin from node 0. In first move, we can either move to node 1 and collect 1 coin or move to node 2 and collect 1 coin. Therefore, the expected number of coins after 1 move starting from node 0 is (1 + 1/2 * (1 + 1)) = 2.
- If we start from node 1, then we will get 1 coin from node 1. In first move, we can either move to node 0 and collect 1 coin or move to node 2 and collect 1 coin. Therefore, the expected number of coins after 1 move starting from node 1 is (1 + 1/2 * (1 + 1)) = 2.
- If we starts with node 2, then we will get 1 coin from node 2. In the first move, we have 3 choices to make: move to node 0 and collect 1 coin, move to node 1 and collect 1 coin or move to node 4 and collect 2 coins. Therefore, the expected number of coins after 1 move starting from node 2 is (1 + 1/3 * (1 + 1 + 2)) = 7/3.
- If we starts with node 3, then we will get 2 coins from node 3. In the first move, we can only move to node 2 and collect 1 coin. Therefore, the expected number of coins after 1 move starting from node 3 will be (2 + 1) = 3.
Since the probability to choose any node as the starting node is (1/4), the expected number of coins are: 1/4 * (2 + 2 + 7/3 + 3) mod (109 + 7) = 333333338
Input: V = 4, E = 4, K = 0, edges[][] = {{0, 1}}, coins[] = {2, 2}
Output: 2
Explanation: Since we cannot make any moves, we can only choose the starting node and collect its coin.
- If we start from node 0, we will get 2 coins.
- If we start from node 1, we will get 2 coins.
Since the probability to choose any node as the starting node is (1/2), the expected number of coins are: 1 / 2 * (2 + 2) mod (109 + 7) = 2.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Depth First Search and Dynamic Programming. We can run a DFS starting from every node and keeping track of the number of moves left. Also maintain a 2D array dp[][] such that dp[i][j] = expected number of coins if we are at node i and have j moves remaining.
Step-by-step algorithm:
Below is the implementation of the algorithm:
333333338
Time Complexity: O(V * E), V is the number of nodes and E is the number of edges.
Auxiliary Space: O(V * E)