This page is still under construction.

Parts of this page are still being built. What you see may change.

Swapping Game

Time limit1sMemory limit128 MB

Summary
Rearrange the letters of the given string into the lexicographically smallest string that fits the per-position allowed letters, or report NO SOLUTION.
Level

Medium7 of 10

Topics
Greedy, Graph
Solved
No attempts yet

Problem

Dongil came up with a game he can play by himself.

The game starts from one string of NN lowercase letters.

Dongil may swap any two letters of the string. He may repeat this operation as many times as he likes, zero times included.

The goal is to build the lexicographically smallest string.

After a few rounds the game felt too easy, so Dongil added one more rule. For every position of the finished string he decides in advance which letters may sit there, like this.

  • The first letter must be a or b.
  • The second letter must be b or c.

The rule applies only to the final string. A string that appears in the middle of the game does not have to obey it.

The rule made the game much harder. Help Dongil and find the lexicographically smallest string he can build while obeying the rule.

Input

The first line has the number of test cases TT. (1≤T≤1001 \le T \le 100)

The first line of each test case has the starting string SS, which consists of NN lowercase letters. (1≤N≤1001 \le N \le 100)

The next NN lines each have a string CiC_i. CiC_i consists of LiL_i letters and lists the letters allowed at position ii of the result. (1≤Li≤51 \le L_i \le 5)

Every letter that appears in CiC_i appears at least once in the starting string SS.

Output

For each test case print, on its own line, the lexicographically smallest string that obeys the rule. If no string obeys the rule, print NO SOLUTION.

Examples2

  1. Example 1

    Input
    2
    abcde
    abcde
    a
    abcde
    abcde
    abcde
    abcde
    ab
    ab
    ab
    abcde
    abcde
    
    Expected output
    bacde
    NO SOLUTION
    
  2. Example 2

    Input
    1
    abc
    abc
    a
    ab
    
    Expected output
    cab