Minimize water to fill all tanks connected by given circuit
Given N tanks connected like a tree, the connections between them in an array Edge, and the capacity of each tank in the array cap, the task is to find the minimum amount of water required to pour into the given tank such that all the tanks are filled.
Note: When a tank is filled, the remaining amount of water is equally distributed among the other tanks which are connected to it except the one which is the source for this tank. Also, the maximum water available is 1018.
Input: N = 4, S = 1, Edges = [[1, 2], [1, 3], [2, 4]], Cap = [1, 1, 1, 1]
Explanation: Initially, 5 unit of water is poured into
tank 1. 2 unit of it flows to tank 2 and
2 unit of it flows into tank 3. From 2
unit of water in tank 2, 1 unit flows into
tank 4 and 1 unit from tank 3 are wasted.
Input: N = 3 and S = 2, Edges = [[1, 2], [2, 3]], Cap = [1, 1, 1]
Approach: This problem can be solved using Depth First Search based on the following idea:
For any depth, the amount of water that needs to flow in every tank as the same as the maximum requirement for a single tank. If this is followed in bottom-up manner we will get the minimum required water in the source.
Follow the steps mentioned below to implement the idea:
- Create an adjacency list for the tree using the given edges.
- Create a visited array to store if a node has been visited or not.
- Now start depth-first traversal from the given start node.
- Add capacity of the current node in answer. Add the maximum cost of dfs in adjacent nodes multiplied by all connected nodes except the parent node.
dfs[node] = cap[node] + (number of child except parent node) * max(dfs(child))
- If dfs(node) is greater than 1018 or dfs(child) is -1 then return -1.
Below is the implementation of the above approach:
Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V)