Grammar
Time limit2sMemory limit1024 MB
Given a context-free grammar over a and b, decide whether the language contains a string with more a characters than b characters.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Graph, Shortest path
- Solved
- No attempts yet
Problem
A formal grammar is a way of describing formal languages. It is written as , where is an alphabet whose elements are called terminals. is the set of nonterminals, is the starting nonterminal, and is the set of production rules, each of the form .
Here, is the set of all strings of one or more elements of (non-empty strings of nonterminals). is the set of all strings of zero or more elements of , including the empty string.
A grammar is context-free if the left side of each rule is exactly one nonterminal. In other words, .
For example, take the alphabet , the nonterminals , and these two rules:
This grammar is context-free.
To generate a language, start from the string consisting of only , then apply production rules one or more times. Applying a rule means finding its left side in the current string and replacing it with its right side. The language generated by the grammar is the set of all strings made only of terminals that can be produced this way.
In the example above, belongs to the language, since . No other strings are generated.
Some grammars generate infinite languages, and others generate empty languages.
You are given a context-free grammar over the terminals a and b. Determine whether the language it generates contains a string with strictly more a characters than b characters.
The nonterminals are numbered from 1 to . The starting nonterminal is always 1.
Input
The input contains one or more test cases.
The first line of each test case contains two integers and , the number of nonterminals and the number of production rules (, ).
Each of the next lines describes one rule. It starts with and , where () is the left side nonterminal and () is the length of the right side. Then symbols follow. Each symbol is either a nonterminal () or a terminal a or b. Symbols are separated by single spaces.
The sum of over all test cases does not exceed 1000. The sum of over all test cases does not exceed 50 000. The input size does not exceed 5 megabytes.
The input ends with a line containing two zeroes.
Output
For each test case, print one line. Print YES if the language contains a string with strictly more a characters than b characters. Otherwise, print NO.