Shortest Accepted Word
Time limit1sMemory limit256 MB
Parse a regular expression over a, b, c and $ into a tree, then compute the shortest lexicographically smallest string each node accepts.
- Level
Medium7 of 10
- Topics
- Dynamic programming, String, Recursion, Implementation
- Solved
- No attempts yet
Problem
In this problem, we consider strings consisting of lowercase Latin letters "a", "b", and "c".
A regular expression is defined recursively as follows.
- A single character "
$" is a regular expression accepting the empty string. - Single characters "
a", "b", and "c" are regular expressions accepting strings "a", "b", and "c", respectively. - If is a regular expression, "
()" is also a regular expression accepting all strings accepted by . - If is a regular expression which is a direct result of applying any of the rules 1--4, its iteration, denoted as "
*", is also a regular expression accepting strings of the form (a concatenation of zero or more strings) where is any non-negative integer and each string is accepted by . - If and are regular expressions which are direct results of applying any of the rules 1--5, their concatenation, denoted simply as "
{}", is also a regular expression accepting strings of the form (a concatenation of and , each of which may be empty) where the prefix is accepted by and the suffix is accepted by . - If and are regular expressions which are direct results of applying any of the rules 1--6, their union, denoted as "
|", is also a regular expression accepting both strings accepted by and strings accepted by .
The restrictions in rules 4--6 are imposed to prevent ambiguities and to prioritize operations: when reading a regular expression, evaluate iteration, then concatenation, then union. Parentheses play the usual role of prioritizing operations enclosed in them. For example, the regular expression "a(bac|ac*)" is read as "accept a followed by either (b followed by a followed by c) or (a followed by zero or more copies of c)".
Given a regular expression , find the shortest string which is accepted by this regular expression . If there are several such strings, find the lexicographically smallest one.
Input
The first line of input contains one integer , the number of test cases ().
Each of the next lines describes a single test case. Each test case description consists of a regular expression which is a string constructed by the above rules. Its length is from 1 to 300 characters.
The sum of all lengths of regular expressions is not greater than 300.
Output
For each test case print a single line containing the shortest string accepted by the given regular expression . If there is more than one such string, print the lexicographically smallest one.
If the answer is an empty string, print a single character "$" instead.