Grammars

A grammar consists of rules composed by one or more productions and one
or more terminal symbols. In this exercise we suppose that the
productions start with an uppercase letter, and that the initial
production is called @I@. For instance, the following grammar generates
all the (non empty) correct parenthesizations:

  ----- --- ------- --- --------- --- -------
  @I@   →   @( )@   |   @( I )@   |   @I I@
  ----- --- ------- --- --------- --- -------

In this example, |( )| is generated by applying the first rule, @( ( )
)@ is generated by applying the second rule and then the first one, @( )
( )@ is generated by applying the third rule and then the first one
twice, etcetera.

Assume that @lambda@ denotes an empty special terminal symbol. Using
this convention, the following grammar generates all the words that
start with @a@ and that contain an even number of @a@s and an odd number
of @b@s:

  ------ --- ---------- --- -------- --- --------
  @I@    →   @a OO@                      
  @OO@   →   @a EO@     |   @b OE@       
  @OE@   →   @a EE@     |   @b OO@       
  @EO@   →   @a OO@     |   @b EE@       
  @EE@   →   @lambda@   |   @a OE@   |   @b EO@
  ------ --- ---------- --- -------- --- --------

Write a program that prints n terms generable with a given grammar. If a
production has r rules (numbered from 0 to r − 1), to decide which rule
to pick, use a generator of pseudorandom numbers with parameters m, a, b
and s, as it is explained in the
exercise problem://problemsjutge.org:problems/i2/roura/camins-aleatoris.pbm:

        int random(int r, int m, int a, int b, int& s) {
            s = (a*s + b)%m;
            return s%r;
        }

Input

Input starts with a natural number p > 0 that indicates the number of
productions. Each production starts with its name and its number of
rules r > 0. Each rule is described with a natural number m > 0 followed
by m names of productions or terminal symbols.

Input ends with the number n of terms that must be generated, followed
by the four natural numbers m, a, b and s that define the generator of
pseudorandom numbers.

Output

Print n lines, each one with the term that results after applying the
rules indicated by the generator of pseudorandom numbers. Use the
productions from left to right inside every rule. Each word must be
preceded by a space.

Observation

The first sentence of the third sample output is the literal translation
of a Catalan tongue twister.

Problem information

Author: Unknown
Translator: Carlos Molina

Generation: 2026-01-25T11:17:14.840Z

© Jutge.org, 2006–2026.
https://jutge.org
