Brainstuck
SRM 668 · 2015-08-31 · by zxqfl
Problem Statement
- + increases the value of the memory cell by 1.
- - decreases the value of the memory cell by 1.
- [ looks at the value of the memory cell. If it is zero, the instruction pointer moves to the matching ] command.
- ] looks at the value of the memory cell. If it is non-zero, the instruction pointer moves to the matching [ command.
A Brainstuck program is valid if and only if:
- There are no unmatched [ or ] characters.
- The execution of the program terminates after a finite number of steps.
Notes
- The ] character which matches a [ character at index i in the string s is at the smallest index j such that j > i and s[i..j] contains an equal number of [ and ] characters.
Constraints
- N will be between 1 and 100, inclusive.
- M will be between 2 and 1,000,000,000, inclusive.
2 1000000000 Returns: 5
The valid programs are ++, -+, +-, --, []. Note that the execution of the program "[]" consists only of a single step: The instruction pointer points to the [ and the value of the memory cell is zero, so during the execution of this command the interpreter moves the instruction pointer to the matching ]. Then, after the command is executed, the interpreter increments the instruction pointer, which moves it past the last character of the program.
3 1000000000 Returns: 12
The valid programs are: +++ -++ +-+ --+ []+ ++- -+- +-- --- []- [+] [-]
5 1000000000 Returns: 92
16 1000000000 Returns: 55450070
13 163 Returns: 64
Submissions are judged against all 18 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class Brainstuck with a public method int countPrograms(int N, int M) · 18 test cases · 2 s / 256 MB per case