UVa 10917
Contents |
[edit] 10917 - A Walk Through the Forest
[edit] Summary
Given an undirected graph, find the number of paths from node 1 to node 2, subject to the constraint that an edge from node A to node B may only be followed if there is any path from B to 2 that is shorter than all possible routes from A to 2.
[edit] Explanation
The constraint sounds unwieldy, but in fact, if there is any path from B to 2 that is shorter than all routes from A to 2, then the shortest path will be it.
Start by running any single-source shortest path algorithm from node 2, the end state. (Dijkstra's Algorithm will do.) Then, figure out which edges can be taken. If D(A) represents the shortest path from A to 2, then an edge from A to B can be taken only if D(A) > D(B). If we consider only those edges that can be traversed at all, we end up with a directed acyclic graph. This strongly suggests that we perform a topological sort on the new graph.
At this point, all that remains to be done is a relatively straightforward DP/memoization, to discover the number of paths that start at 1 and end at 2.
[edit] Optimizations
None are really needed - the number of nodes is at most N and there is at most one (undirected) edge between any two nodes. The above algorithm requires O(N2) for a naive implementation of Dijkstra's, O(N2) for the creation of the DAG, O(V + E) = O(N2) for the topological sort, and another O(N2) for the DP, for a total quadratic running time. This should have no problems running in time.
[edit] Input
5 6 1 3 2 1 4 2 3 4 3 1 5 12 4 2 34 5 2 24 7 8 1 3 1 1 4 1 3 7 1 7 4 1 7 5 1 6 7 1 5 2 1 6 2 1 0
[edit] Output
2 4