During a battle, Sheldor the conqueror notices that his cities are in the form of a Directed Acyclic Graph , i.e, all the roads are one-way and there is no sequence of roads starting from a city that comes back into it.
City 1 is completely under Sheldor's control and he uses it as the base shelter for his troops. He intends to send a number of troops to City 30. How many distinct paths could these troops take?
Input File: Link
Input Format and Details:
u v
in that order. This means that there is a
directed edge
from
u
to
v
.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
For each node, we count and store the number of ways it can reach the final node. Let p a t h s ( i ) be the number of ways to reach the final node. The number of ways for node i to reach the final node is the sum of the number of ways of i 's children to reach the final node. Mathematically, this is
p a t h ( i ) = j ∈ c h i l d ( i ) ∑ p a t h ( j )
Arriving at this equation we know that we must find p a t h ( i ) in the correct order, ie if we haven't compute the p a t h ( j ) we cannot compute p a t h ( i ) . To deal with this, Agnishom's idea is to get the topological sort and compute p a t h ( ) according to that order. The definition of topological sort is that all children will be computed first before any of their parents, hence we will not miss out any children's p a t h ( ) . My solution is to straightly compute from the beginning node and recursively find its way to the final node - the idea of Depth-First Search.