Waterpark

Interview

Time limit1sMemory limit128 MB

Summary
Count the number of distinct paths from point 1 to point n in a DAG where every edge goes from a lower to a higher numbered point.
Level

Medium4 of 10

Topics
Dynamic programming, Graph
Solved
No attempts yet

Problem

The local waterpark has a great slide complex, with many paths crisscrossing down the hill. There is one start point and one end point, but at various points you can turn and take different paths. Walter and Wanda wonder exactly how many different ways there are to go down the slide. Can you solve their problem?

More precisely, there are nn marked points (including the start at point 11 and the end at point nn) where the paths down the hill may split or merge. All paths move down the hill toward higher-numbered points; some paths cross over others without meeting, but we do not have to worry about that, nor about collisions between sliders. The task is simply to determine the number of different sequences of marked points one can follow down the hill.

For example, at one small waterpark there are 44 points, with direct slides from 11 to points 22 and 44; from 22 to 33 and 44; and from 33 to 44. There are 33 ways down the hill: you can go (1,2,3,4)(1,2,3,4), (1,2,4)(1,2,4), or (1,4)(1,4).

Hint: think about starting from the bottom of the slide.

Input

The first line contains a single integer nn (1≤n≤99991 \le n \le 9999), the number of marked points. Each of the following lines contains a point pair of the form x y, where 1≤x<y≤n1 \le x < y \le n, indicating a direct slide from point xx to point yy. For example, 1234 8765 indicates a direct slide from point 12341234 to point 87658765. The list ends with the point pair 0 0.

Output

Print a single integer: the number of different paths from point 11 to point nn. You may assume this number is less than 2302^{30}. If there is no path from point 11 to point nn, the number of paths is 00.

Examples2

  1. Example 1

    Input
    4
    1 2
    1 4
    2 3
    2 4
    3 4
    0 0
    
    Expected output
    3
    
  2. Example 2

    Input
    2
    1 2
    0 0
    
    Expected output
    1