Magicka (Small)
InterviewTime limit5sMemory limit512 MB
Simulate invocations in order, combining the last two list elements when a rule matches and clearing the whole list when opposed elements meet.
- Level
Easy3 of 10
- Topics
- Simulation, Stack
- Solved
- No attempts yet
Problem
You are a wizard and you invoke eight base elements. Each base element is one of the characters Q, W, E, R, A, S, D, F. Invoking an element appends it to your element list. If you invoke W and then invoke A (call it "invoking WA" for short), the element list becomes [W, A].
The input gives pairs of base elements that combine into a non-base element, one of the other 18 capital letters. Suppose Q and F combine into T. The moment the two elements of such a pair sit in the last two positions of the element list, both leave the list at once and the element they form takes their place. In this example, a list that becomes [A, Q, F] or [A, F, Q] turns into [A, T].
The input also gives pairs of base elements that are opposed to each other. Right after you invoke an element, if it was not combined into another element and the list holds any element opposed to it, the whole element list is cleared.
Suppose Q and F combine into T, and R and F are opposed. Invoking the following, left to right, gives these results.
- QF → [T] (Q and F combine into T)
- QEF → [Q, E, F] (Q and F never sit at the end of the list together, so they do not combine)
- RFE → [E] (F and R are opposed, so the list is cleared, and then E is invoked)
- REF → [] (F and R are opposed, so the list is cleared)
- RQF → [R, T] (QF combines into T, so the list is not cleared)
- RFQ → [Q] (F and R are opposed, so the list is cleared)
Given the order of the elements to invoke, report what the element list holds once every invocation is done.
Input
The first line holds the number of test cases . Each of the next lines holds one test case with the following space separated values in order.
First an integer , then strings of three characters each. A string holds two base elements followed by a non-base element, which means that the two base elements combine into that last element. Next an integer , then strings of two characters each, each holding two base elements that are opposed to each other. Finally an integer and one string of characters, the order of the base elements you invoke. You invoke them one at a time, starting from the leftmost character.
Limits
- A pair of base elements appears in at most one combination. The same pair may appear in a combination and also be opposed.
- No base element is opposed to itself.
- Unlike in the computer game Magicka, the element list has no length limit.
Output
For each test case print one line in the form "Case #x: y". Here x is the case number starting from 1, and y is the final element list written as "[e0, e1, ...]", where ei is the i-th element of the list. Separate elements with one comma and one space. Print "[]" for an empty list.