Genotypes
Time limit1sMemory limit128 MB
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 , meaning that gene may turn into the pair of genes .
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 with . Each of the next 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 with . Each of the next lines contains one genotype, a non-empty word of at most capital letters A–Z.
Output
For the -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.