#P6701. [POI 1997] Genotype

[POI 1997] Genotype

Background

Genotype is a unique gene string.

Problem Description

We can use uppercase English letters A-Z to describe a Genotype, where each letter represents one gene.

We define a “split” rule, consisting of three uppercase letters A1A2A3A_1A_2A_3, meaning that A1A_1 can “split” into A2A3A_2A_3.

Now you are given nn “split” rules and kk Genotypes. Determine whether each Genotype can be obtained from a specific string consisting only of the uppercase letter S by applying the “split” rules. If it can, output the minimum possible length of that specific string. If it cannot, output NIE.

Input Format

The first line contains an integer nn, the number of “split” rules.
The next nn lines each contain three uppercase letters A1,A2,A3A_1,A_2,A_3, representing one “split” rule.
The next line contains an integer kk, the number of given Genotypes.
The next kk lines each contain several uppercase letters, representing one Genotype.

Output Format

Output kk lines:

  • If no specific string can produce this Genotype by applying the “split” rules, output NIE.
  • Otherwise, output the minimum length of such a specific string.
6
SAB
SBC
SAA
ACA
BCC
CBC
3
ABBCAAABCA
CCC
BA
3
1
NIE

Hint

Constraints

For 100%100\% of the testdata, 1n,k20001 \le n,k \le 2000, and the maximum length of a Genotype is 100100.

Translated by ChatGPT 5