Chomsky Normal Form Grammar
Time limit5sMemory limit256 MB
Decide whether a given string of up to 1000 lowercase letters belongs to the language generated from start symbol S by a CNF grammar.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Intervals
- Solved
- No attempts yet
Problem
A context free grammar is given in Chomsky Normal Form (CNF). Such a grammar consists of the following.
- a set of nonterminal symbols
- a set of terminal symbols
- a start symbol that belongs to
- a set of rules of the form or , where and
For , the language generated by is defined as follows.
The language generated by the grammar is the language of the start symbol, . Given a string , decide whether belongs to .
Input
The first line contains the string . It consists of lowercase letters only and its length is between 1 and 1000.
From the second line to the end of the file, each line holds one grammar rule. Nonterminal symbols are written as uppercase letters and terminal symbols as lowercase letters. A line ABC of length 3 means the rule , and a line Aa of length 2 means the rule . The start symbol is always S. At least one rule is given, and the same rule can appear more than once.
Output
Print 1 on one line if belongs to the language generated by the grammar, and 0 otherwise.