Mhocskian Languages
Time limit2sMemory limit512 MB
Given a context-free grammar in Chomsky normal form and a list of words, decide for each word whether the start variable can derive it.
- Level
Medium7 of 10
- Topics
- Dynamic programming, String, Implementation, Backtracking
- Solved
- No attempts yet
Problem
Linguists are studying Mhocskian, the language of the native inhabitants of Mhocsky Island. They have found a description of how the natives build words, together with a list of candidate words, and want to know which of those words are valid Mhocskian words.
Words in Mhocskian are built from two kinds of symbols.
- A variable is an uppercase letter used only while a word is being built.
- A terminal is a lowercase letter that actually appears in a finished word.
There are two kinds of rules.
- replaces the variable with the two variables , in that order.
- replaces the variable with the terminal .
One of the variables is the start variable. A word made up of lowercase letters is a valid Mhocskian word if, starting from the start variable, some sequence of rule applications produces exactly . For instance, if the start variable is with rules , , and , then applying , then and derives the word , so is valid.
Given the rules and a list of words, decide for each word whether it is a valid Mhocskian word.
Input
- The first line contains two integers and : the number of variables and the number of terminals.
- The second line contains space-separated uppercase letters, the variables. The first of them is the start variable.
- The third line contains space-separated lowercase letters, the terminals.
- The fourth line contains an integer . Each of the next lines has the form
V tand represents a rule . - The next line contains an integer . Each of the next lines has the form
V V1 V2and represents a rule . - The next line contains an integer . Each of the next lines contains one word made entirely of lowercase letters.
Output
Output lines. On line , print 1 if the -th word is a valid Mhocskian word, and 0 otherwise.
Constraints
- Each word in the list has length between and .