Search code examples
arraysalgorithmobjectmath

Linked Objects & Task Count


Tasks for one object can be run coupled with another and if that is the case the primary linked object will not run it's own task (coupled instead of solo for every object that is linked to it).

Say I have the following tasks I need to run, I need the answer to be 4 tasks.

  • One
  • Two (linked to One)
  • Three
  • Four (linked to Three)
  • Five (linked to Three)
  • Six

There will be 4 tasks (3 of which are run with the linked object as 1 instead of 2). So 1 (One + Two) & 1 (Three + Four) & 1 (Three + Five) & 1 (Six).

I have tried different examples but cannot figure out how to compute the number of tasks required.

Another example:

  • One
  • Two (linked to One)
  • Three
  • Four (linked to Three)
  • Five

In this case it has to be 1 (One + Two) & 1 (Three + Four) & 1 (Five) = 3 tasks.


Solution

  • This is a graph problem. The first example can be visualised as:

                         (_root_)
                        /    |   \
                     One   Three  Six
                    /      /   \
                   Two  Four   Five
    

    The second example:

                         (_root_)
                        /   |    \
                     One  Three  Five
                    /       |
                  Two     Four
    

    The solution consists of listing all leaf-nodes (and if needed, the list of nodes on the path from the root to each leaf).

    So:

    • Create the tree from the node and edge information you have in the input (the root is implicitly defined)

    • Traverse the tree with a depth-first traversal to find all (paths to) leaf nodes.