Given a DAG and multiple sources S1 .. Sn, we define a valid node as a node that is reachable from all sources. Find out all the valid nodes which don't have a valid parent.
Effectively, find the direct-multi-source children of S1 .. Sn
Example: In the following DAG, S1, S2, S3 are the sources. Nodes a, b, c are reachable via all sources. However, node c has a parent which is also reachable via all sources.
So the top view is a, b
The naive algorithm for this would be to
- For each source, find the set of reachable nodes
- Take the intersection of these sets to find all valid nodes
- Perform a multi-source BFS from all sources. When moving from
parent -> childkeep track of whether the parent was a valid node or not. Any valid node which was reached via a parent which is also a valid node gets discarded.
This algorithm takes O((V+E) * S) time because of step 1.
V = number of vertices
E = number of edges
S = number of sources
Is there a faster algorithm? Can this be done in O(V+E)?
