A contract-assembly tool stores a library of named clauses. Each clause's text is a sequence of space-separated tokens, and a token is either a literal word or a reference to another clause written as {clause_name}, which must be replaced by that other clause's own fully resolved text wherever it appears. A master document is written the same way, mixing literal words with clause references. Clause references never form a cycle, and every clause name used as a reference is guaranteed to be defined in the library. Produce the fully expanded master document, with every reference — direct or nested — replaced all the way down to plain words.
Line 1: an integer n — the number of clause definitions. Next n lines: each line is "name text", where name is the clause's name and text is its token sequence (text may be empty, in which case the line contains only the name and nothing after it). Names are unique. Last line: the master document's token sequence (it may be empty, i.e. a blank line).
Print a single line: the fully expanded master document, with tokens separated by single spaces. If the expansion has zero tokens, print an empty line.
Example 1
Input
3
liability {refund_policy} applies
refund_policy full refund within 30 days
warranty {liability} extended coverage
the {warranty} is standardExpected
the full refund within 30 days applies extended coverage is standard
Explanation
refund_policy has no references, so it stays "full refund within 30 days". liability's text is "{refund_policy} applies", so substituting the reference gives "full refund within 30 days applies". warranty's text is "{liability} extended coverage", giving "full refund within 30 days applies extended coverage". The document is "the {warranty} is standard", so replacing {warranty} with its expansion yields "the full refund within 30 days applies extended coverage is standard".
Example 2
Input
2
greeting hello there
farewell goodbye friend
{greeting} and {farewell}Expected
hello there and goodbye friend
Explanation
greeting expands to "hello there" and farewell expands to "goodbye friend". The document "{greeting} and {farewell}" substitutes each reference in place, leaving the literal word "and" untouched between them, giving "hello there and goodbye friend".
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →