![]() |
VOOZH | about |
Given an undirected graph with N vertices and N edges that contain only one cycle, and an array arr[] of size N, where arr[i] denotes the value of the ith node, the task is to check if the cycle can be divided into two components such that the sum of all the node values in both the components is the same.
Examples:
Input: N = 10, arr[] = {4, 2, 3, 3, 1, 2, 6, 2, 2, 5}, edges[] = {{1, 2}, {1, 5}, {1, 3}, {2, 6}, {2, 7}, {2, 4}, {4, 8}, {4, 3}, {3, 9}, {9, 10} }
👁 Image
👁 Image
Output: Yes
Explanation: By removing the edges 1-2 and 3-4, the sum of all the node values of both the generated components is equal to 15.
Input: N= 4, arr[] = {1, 2, 3, 3}, edges[] = {{1, 2}, {2, 3}, {3, 4}, {2, 4}}
👁 Image
Output: No
Explanation: No possible way exists to obtain two equal sum components by removing an edges from the cycle.
Approach: The idea to solve this problem is to first find the nodes which are part of the cycle. Then, add the value of each node that is not a part of the cycle to its nearest node in the cycle. The final step involves checking whether the cycle can be divided into two equal sum components. Below are the steps:
Below is the implementation of the above approach:
Yes
Time Complexity: O(N)
Auxiliary Space: O(N)