Bilda ord
Time limit1sMemory limit1024 MB
Count permutations of N distinct letters that satisfy rules forcing a letter into given positions or requiring one letter to come immediately before another.
- Level
Medium6 of 10
- Topics
- Backtracking, Combinatorics, Implementation, Bit manipulation
- Solved
- No attempts yet
Problem
Fatimeh is studying her native language, which uses the Arabic alphabet. Right now she is working on an exercise where she has to answer how many ways she can form a word from the given letters.
If the exercise had been in Swedish, it could look like this:
r M e a
Since four letters are given, Fatimeh knows she has to test permutations. But because the letter M is "large", we know it must be placed at the beginning of the word. With that condition, only words can be formed, for example , but not . The Arabic alphabet does not have uppercase and lowercase letters in the same way, but it has other rules about where in the word a letter may appear, including in relation to other letters.
In this problem we assume there are two types of restrictions: either a letter must come immediately before another letter, or a letter may only stand in certain positions. Examples of these rules and the notation we use are in the following table:
Write a program that computes in how many ways different letters (called A, B, C,... etc. for simplicity) can be placed, given a number of rules of these two types.
Input
The first line contains two integers, the number of letters and the number of rules . Then follow lines, each describing one rule according to the notation above. A given letter cannot appear first in more than one rule of each type. Note that all position numbers are written with two digits.
Output
The program shall print one integer: the number of ways the letters can be placed. The answer will always be less than 10 million.