algorithm - Check whether 2 nodes have any common parent(s) in a DAG graph -


the input is:

an int[][], each sub array contains 2 int {parent, child}, means there path parent -> child.

e.g

{ { 1, 3 }, { 2, 3 }, { 3, 6 }, { 5, 6 }, { 5, 7 }, { 4, 5 }, { 4, 8 }, { 8, 9 } }; 

or tree structure:

   1   2   4    \ /   / \     3   5   8      \ / \   \       6   7   9 

the task is:

Giving 2 value (x, y), return boolean value, indicate whether have common parent(s).

sample input , output:

 [3, 8] => false [5, 8] => true [6, 8] => true 

my idea:

  • represent input data dag graph, in data stored in map map<integer, linkedlist<integer>>, key vertex, value adjacency list. , direction in graph reversed (compared input data) child -> parent, easy search parent.
  • use function findavailableparents(integer vertex) find parents (direct , indirect) single vertex, , return set<integer>.
  • thus, need call findavailableparents() once each input vertex, compare whether 2 returned sets have intersection. If yes, have common parent; otherwise, don't.

my questions are:

  • the time complexity in solution above between o(1) ~ o(e), right? (e edge counts in graph)
  • is there better solution?

suppose have multiple inputs, bfs take around o(e) time process each input.

all inputs can queried in o(logn) if pre computation should take o(nlogn) time

basically want find least common ancestor of nodes
thread in topcoder discusses logic tree can extended dag
can refer this question further ideas

if lca exists between 2 nodes, have common parent


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -