Chomsky Normal Form Grammar

No attempts yetTime limit5sMemory limit256 MB

Problem

A context free grammar is given in Chomsky Normal Form (CNF). Such a grammar consists of the following.

  • a set NN of nonterminal symbols
  • a set TT of terminal symbols
  • a start symbol SS that belongs to NN
  • a set RR of rules of the form ABCA \to BC or AaA \to a, where A,B,CNA, B, C \in N and aTa \in T

For ANA \in N, the language L(A)L(A) generated by AA is defined as follows.

L(A)={wzwL(B), zL(C), ABCR}{aAaR}L(A) = \{\,wz \mid w \in L(B),\ z \in L(C),\ A \to BC \in R\,\} \cup \{\,a \mid A \to a \in R\,\}

The language generated by the grammar is the language of the start symbol, L(S)L(S). Given a string xx, decide whether xx belongs to L(S)L(S).

Input

The first line contains the string xx. 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 ABCA \to BC, and a line Aa of length 2 means the rule AaA \to a. 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 xx belongs to the language generated by the grammar, and 0 otherwise.