100 atcoder#ABC219C. [ABC219C] Neo-lexicographic Ordering

[ABC219C] Neo-lexicographic Ordering

Score : 300300 points

Problem Statement

Takahashi, who governs the Kingdom of AtCoder, has decided to change the alphabetical order of English lowercase letters.

The new alphabetical order is represented by a string XX, which is a permutation of a, b, \ldots, z. The ii-th character of XX (1i26)(1 \leq i \leq 26) would be the ii-th smallest English lowercase letter in the new order.

The kingdom has NN citizens, whose names are S1,S2,,SNS_1, S_2, \dots, S_N, where each SiS_i (1iN)(1 \leq i \leq N) consists of lowercase English letters. Sort these names lexicographically according to the alphabetical order decided by Takahashi.

What is the lexicographical order?

Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. As a more formal definition, here is the algorithm to determine the lexicographical order between different strings SS and TT.

Below, let SiS_i denote the ii-th character of SS. Also, if SS is lexicographically smaller than TT, we will denote that fact as S<TS \lt T; if SS is lexicographically larger than TT, we will denote that fact as S>TS \gt T.

  1. Let LL be the smaller of the lengths of SS and TT. For each i=1,2,,Li=1,2,\dots,L, we check whether SiS_i and TiT_i are the same.
  2. If there is an ii such that SiTiS_i \neq T_i, let jj be the smallest such ii. Then, we compare SjS_j and TjT_j. If SjS_j comes earlier than TjT_j in alphabetical order, we determine that S<TS \lt T and quit; if SjS_j comes later than TjT_j, we determine that S>TS \gt T and quit.
  3. If there is no ii such that SiTiS_i \neq T_i, we compare the lengths of SS and TT. If SS is shorter than TT, we determine that S<TS \lt T and quit; if SS is longer than TT, we determine that S>TS \gt T and quit.

Constraints

  • XX is a permutation of a, b, \ldots, z.
  • 2N500002 \leq N \leq 50000
  • NN is an integer.
  • 1Si10(1iN)1 \leq |S_i| \leq 10 \, (1 \leq i \leq N)
  • SiS_i consists of lowercase English letters. (1iN)(1 \leq i \leq N)
  • SiSjS_i \neq S_j (1i<jN)(1 \leq i \lt j \leq N)

Input

Input is given from Standard Input in the following format:

XX

NN

S1S_1

S2S_2

\vdots

SNS_N

Output

Print NN lines. The ii-th line (1iN)(1 \leq i \leq N) should contain the ii-th smallest name when the citizens' names are sorted according to the alphabetical order decided by Takahashi.

bacdefghijklmnopqrstuvwxzy
4
abx
bzz
bzy
caa
bzz
bzy
abx
caa

In the new alphabetical order set by Takahashi, b is smaller than a and z is smaller than y. Thus, sorting the citizens' names lexicographically would result in bzz, bzy, abx, caa in ascending order.

zyxwvutsrqponmlkjihgfedcba
5
a
ab
abc
ac
b
b
a
ac
ab
abc