3

I have DAG stored as an array. How can I assign priorities to the DAG in a way that parent node gets the highest priority and all leaf nodes the lowest priority?

If I have a DAG as following

    A       # A -> B,C                      # A     
   / \      # B -> D        ----->          # B C   //can be used in parallel
  C   B     # C -> E                        # D 
  \    \    # D -> E                        # E
   \   D    # E ->                             
    \ /
     E

I have both parent and children stored in the array which I am using as DAG.

Topological Sort returns a linear list e.g. A,C,B,D,E only.

SMUsamaShah
  • 7,677
  • 22
  • 88
  • 131
  • Can you show us your code and what you've tried? Please read [ask] – Software Engineer Jan 13 '15 at 16:52
  • @EngineerDollery I am trying to schedule jobs based on DAG. First job must be executed first. I am storing job, its parent and child including some other stuff in the map. In a case as I have shown in example I don't know how to run D only when both A and C have finished. – SMUsamaShah Jan 13 '15 at 16:59

1 Answers1

2

I think what you're looking for is called a topological ordering, a way of ordering the nodes in a DAG so that no node appears before each of its parents. Fortunately, topological orderings can be found very efficiently (in linear time) using various topological sorting algorithms, including one based on a simple DFS of the DAG.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Yes it is topological ordering that I was looking for. Thank you! – SMUsamaShah Jan 13 '15 at 17:13
  • Is there any library that I can easily add without much hassle? Currently I am using Map to store the Objects including both its input and outputs links. – SMUsamaShah Jan 13 '15 at 17:19
  • 1
    @LifeH2O I don't know of any such library off the top of my head, but even if there isn't one these algorithms are really easy to code up. Just do a DFS over the graph, starting from each node, and list the nodes off in the order in which you finish processing them. Then, reverse that ordering to get back a topological ordering. – templatetypedef Jan 13 '15 at 17:24
  • It worked fine but what about parallel jobs? With topological sort I only get one at a time. – SMUsamaShah Jan 14 '15 at 10:21
  • Topological sort plus http://stackoverflow.com/a/5057093/342095 solved the problem – SMUsamaShah Jan 16 '15 at 17:58