// CECR 2012 // Problem E: Word Equations // Correct solution, O(kp) // Author: Jakub Pachocki import java.io.*; import java.util.*; class Solver { int position; void dfs(String symbol, Map grammar, String pattern, Set visited) { if (visited.contains(symbol)) { return; } visited.add(symbol); if (grammar.get(symbol).length == 1) { String word = grammar.get(symbol)[0]; for (int i = 0; i < word.length() && position < pattern.length(); ++i) { if (word.charAt(i) == pattern.charAt(position)) { ++position; visited.clear(); } } } else { dfs(grammar.get(symbol)[0], grammar, pattern, visited); dfs(grammar.get(symbol)[1], grammar, pattern, visited); } } void solve() throws IOException { Reader.init(System.in); int nCases = Reader.nextInt(); for (int testCase = 0; testCase < nCases; ++testCase) { Map grammar = new HashMap(); int n = Reader.nextInt(); for (int i = 0; i < n; ++i) { String symbol = Reader.next(); Reader.next(); String original = Reader.next(); if (original.charAt(0) < 'a') { Reader.next(); grammar.put(symbol, new String[]{original, Reader.next()}); } else { grammar.put(symbol, new String[]{original}); } } String startSymbol = Reader.next(); String pattern = Reader.next(); Set visited = new HashSet(); position = 0; dfs(startSymbol, grammar, pattern, visited); System.out.println(position == pattern.length() ? "YES" : "NO"); } } } public class E { public static void main(String[] args) throws IOException { (new Solver()).solve(); } } /** Class for buffered reading int and double values */ class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }