Editorial for COCI '06 Contest 3 #5 Bicikli
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 to vertex , then comes before 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 we calculate the number of routes from vertex to that vertex: examine the edges going into and add up the numbers of ways to reach the preceding vertices (those numbers have already been calculated by now).
Comments