Editorial for COCI '06 Contest 3 #5 Bicikli


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

We model the network of cities and roads with a directed graph.

Note that vertices unreachable from the start node and vertices from which the end node is not reachable are of no use in constructing the bicycle route – we can remove them from the graph.

An infinite number of routes exist only if there is a cycle in the new graph. If there is a cycle, we can go from the start node to the cycle, go about the cycle any number of times and then continue on to the end node.

If there are no cycles, then the number of routes is finite and the graph is said to be acyclic (directed acyclic graph, DAG). Such a graph has what is called a topological ordering: if there is a path from vertex A to vertex B, then A comes before B in the topological ordering. We can find one topological ordering of the graph using a depth-first-search.

Once we've found a topological ordering, we consider vertices in that order and for each vertex V we calculate the number of routes from vertex 1 to that vertex: examine the edges going into V and add up the numbers of ways to reach the preceding vertices (those numbers have already been calculated by now).


Comments

There are no comments at the moment.