Constrained Permutations
InterviewTime limit1sMemory limit128 MB
Count permutations of 1..n (n at most 9) that satisfy given ordering constraints x before y.
- Level
Easy2 of 10
- Topics
- Brute force, Combinatorics, Implementation, Recursion
- Solved
- No attempts yet
Problem
A permutation of the numbers is a linear ordering of those numbers. For example, there are permutations of : they are , , , , , and . Another way to think of it is drawing disks numbered to from a bag (without replacement) and recording the order in which they come out.
The number of permutations of is written , which we call " factorial."
In this problem you are given an integer and a series of constraints on the ordering of the numbers. Each constraint is a pair meaning that must come before in the permutation.
Output the number of permutations that satisfy all of the constraints.
Input
The input consists of lines. The first line contains the integer . The second line contains the integer , the number of constraints. Each of the following lines contains two distinct integers and in the range , meaning that must come before .
Output
Output a single integer: the number of permutations of that satisfy all constraints.