This is a classic CS problem I encountered in my work:
I have a list of resources I need to load. each resource has a list of constraints it needs in order to load and when loaded satisfies other constraints that other resources may need. In example: resource X has a,b,c as constraints so it can only load when a,b and c are fulfilled. when loaded, X satisfies constraints n and m which are needed by resource Y which also needs constraint p in order to load so when another resource will load and satisfy the p constraint, Y will load, and in turn satisfy other constraints.
The list of constraints needed by all resources is final, meaning that each resource may need several constraints and each constraint may be needed by several resources.
Also, one resource needs null constraints in order to load hence must be the first to load.
Ok, after this long explanation here is my question:
How can I find the best loading sequence of the resources when all I know in advance is which constraints are needed per resource but do not know (in advance) which constraints are satisfied by a resource once loaded?
hope my explanation was clear enough…
thanks!
EDIT
Simple Solution:
Create a Bipartite Graph with n Vertices (resources) and m Vertices (constraints). – O(n + m)
Hold the constraints in some lookup table data structure (i.e. a hash table).
Draw edges between resource vertices and constraint vertices whenever a resource needs that constraint.
Create a list L of resources, initially empty. (this is the order in which to load the resources).
Create a set R of resources, initiallly empty. (this is the set of resources which can be added currently). – O(1)
Add the one resource that has 0 constraints to R. – O(1)
while R is not empty:
{
Get some resource r from R – O(1)
Add r to L – O(1)
Let S be the set of all constraints that the resource r fulfills when being loaded.
Foreach constraint c in S lookup the constraint vertex and remove all links going to this vertex. If at the other side of the link, there are no more links (meaning that the resource vertex is now ready to be loaded), add that vertex to R. – O(|S|)
}
TOTAL RUNNING TIME: O(n * |S|), where |S| is the maximum number of constraints fulfilled by a single resource.