Problem 434
Count Paths in a DAG
Medium · 20 pts · Graph, Topological Sort, Dynamic Programming
Problem
A directed acyclic graph has N nodes labelled 1 to N. Count the different directed paths from node 1 to node N, modulo 1000000007. Two paths are different if they use a different sequence of edges. Process the nodes in topological order: the number of ways to reach a node is the sum of the numbers of ways to reach each node with an edge into it. Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).
Input
First line: N and M. Next M lines: a directed edge u v.
Output
Print the number of paths modulo 1000000007.
Constraints
1 <= N <= 100000; 0 <= M <= 200000; the graph has no cycles
Example input
4 5 1 2 1 3 2 4 3 4 1 4
Example output
3
Explanation
With edges 1→2, 1→3, 2→4, 3→4 and 1→4, there are three paths from 1 to 4: 1-2-4, 1-3-4 and the direct edge 1-4.