This page is still under construction.

Parts of this page are still being built. What you see may change.

Genotypes

Time limit1sMemory limit128 MB

Summary
Given budding rules A1 -> A2 A3, decide for each target word whether it can be derived from some number of supergenes S, and report the minimum count.
Level

Medium7 of 10

Topics
Dynamic programming, Intervals, String, Implementation
Solved
No attempts yet

Problem

A genotype is a finite sequence of genes. It can be written as a word made of the capital letters A–Z, where different letters stand for different kinds of genes.

A gene can bud and thereby turn into a pair of new genes. These transformations are governed by a finite set of rules. Each budding rule is written as three capital letters A1A2A3A_1A_2A_3, meaning that gene A1A_1 may turn into the pair of genes A2A3A_2A_3.

The letter S denotes a special kind of gene called a supergene. Breeding a genotype starts from a sequence of supergenes and proceeds by repeatedly budding chosen genes according to the rules.

Given a set of budding rules and several genotypes, write a program that, for each genotype, decides whether it can be bred from some finite sequence of supergenes and, if so, reports the minimal number of supergenes in such a sequence.

Input

The first line contains one integer nn with 1≤n≤100001 \le n \le 10000. Each of the next nn lines contains one budding rule, written as a word of three capital letters A–Z. The second or the third letter of a rule may denote a supergene.

The next line contains one integer kk with 1≤k≤100001 \le k \le 10000. Each of the next kk lines contains one genotype, a non-empty word of at most 100100 capital letters A–Z.

Output

For the ii-th genotype print a single line containing either:

  • one positive integer, the minimal number of supergenes in a sequence from which that genotype can be bred, or
  • the word NIE (Polish for "no") if the genotype cannot be bred at all.

Examples1

  1. Example 1

    Input
    6
    SAB
    SBC
    SAA
    ACA
    BCC
    CBC
    3
    ABBCAAABCA
    CCC
    BA
    
    Expected output
    3
    1
    NIE