Splitting an integer array into 2 unrelated parts
Given an int array (each element value is equal to it) the lengths of links n
and m
between array elements. Divide the array into 2 parts (all elements in the part must be unconnected with respect to the given m
connections).
Conclusion true
, if such a section exists, otherwise false
.
Here are 3 examples:
-
Given array:
{0, 1, 2, 3}
These compounds:
0-1
,2-3
(0 is connected to 1, 2 is connected to a 3)The output should be:
true
(sections{0,3}
,{1,2}
) -
Given array:
{0, 1, 2}
These compounds:
1-2
,0-1
,0-2
The output should be:
false
(no 2 sections contain only unrelated items) -
Given array:
{0,1}
Connection data:
0-1
The output should be:
true
(sections{0}
,{1}
)
My current approach is: form all possible connections between the elements of the array and save them, remove the m
incoming connections from my saved ones, check if the rest of the connections form 2 sections of the given array. This solution is too slow (I suspect it takes too long to create all possible connections).
source to share
The problem is to check if a given plot is bipartite , that is, 2-colorable , which can be done efficiently using depth-first search . Start with an arbitrary node, giving it any of the two colors. For each repeating edge, provide a target node color other than the color of its parent. If this is not possible, stop searching as the input is not bipartite. Otherwise, you've created a 2-color chart that displays two sections.
source to share