Finite automaton
Time limit3sMemory limit1024 MB
Build the smallest DFA that accepts exactly the base-B numbers, read most significant digit first, that are divisible by M.
- Level
Medium7 of 10
- Topics
- Math, Number theory, Implementation
- Solved
- No attempts yet
Problem
Today Vasya learned what a deterministic finite automaton (DFA) is, and he is eager to tell everyone about it.
A DFA has states. At any moment during its work, the automaton is in exactly one of these states. Its input is an arbitrary string. After the work ends, the automaton reports whether the string is acceptable.
The automaton works as follows:
- At the start, the automaton is in the start state, which is always marked as such.
- It reads all symbols of the string from left to right. After reading each symbol, it can switch to a different state, as described below.
- After the whole string is read, the automaton decides the answer from the state it ended in.
For each state and each possible symbol , the automaton defines the state it moves to after reading while in state . That new state can be itself or another state. Each state also has a fixed answer (accepted or not) for the case where the automaton finishes there.
Vasya took the first seminar on the subject, built all sorts of DFAs, and received the following homework. Build a DFA that, given a non-negative integer written in base , accepts those and only those integers divisible by the given modulus .
To keep things simple, Vasya assumes that the input number:
- starts with its most significant digit (written on the left, big-endian);
- can have leading zeroes;
- can be empty. An empty input is zero and is always divisible by .
Vasya is a born perfectionist. He wants to learn how to build DFAs that meet the requirements with the smallest possible number of states. He asked you to help him.
Input
The only line of the input contains two integers: , the base of the positional numeral system in which the input number is written, and , the modulus that all accepted numbers must be divisible by and all rejected numbers must not be divisible by (, ).
Output
Print the description of the smallest DFA that meets the requirements.
The first line contains two integers: , the number of states (), and , the start state number (). States are numbered consecutively from 0.
The second line contains space-separated symbols. The -th symbol is the answer the automaton gives when it ends in state (). The symbol is 'G' if the string is accepted and 'B' otherwise.
The next lines each contain integers. The -th number on the -th of these lines is the state the automaton ends up in after reading digit while in state (, ). Each number can be any integer from 0 to .
Hint
Shown below is the DFA used in the sample. The letter 'S' and a number are shown near each state. The bold arrow points to the start state. Each normal arrow shows the state the DFA moves to after reading the digit written near it.
