#P11089. Lexicographically Minimum Crystal Sequence
Lexicographically Minimum Crystal Sequence
Lexicographically Minimum Crystal Sequence
Given a sequence of \(n\) crystals arranged from left to right, where each crystal belongs to one of \(k\) types represented by the first \(k\) lowercase English letters, you are allowed to remove crystals under certain conditions. The allowed removals are dictated by a \(k\times k\) table \(A\) whose entries are either 0 or 1. In particular, if \(A_{i,j}=1\), then whenever a crystal of type corresponding to the \(i\)th letter is immediately to the left of a crystal of type corresponding to the \(j\)th letter, the crystal of type \(j\) can be removed in one move.
You may perform these deletion moves in any order. Note that a crystal can only be removed if it has an immediate left neighbor at the time of deletion. However, even if a crystal is eventually removed, it might have served as the left neighbor for the deletion of another crystal before being deleted. In other words, the order of removals can be chosen arbitrarily as long as each removal move satisfies the corresponding allowed condition at the moment of removal.
Your task is to obtain the lexicographically smallest final string (i.e. the sequence of crystal types that are not removed) that can be achieved by a sequence of allowed removals.
Lexicographical order is defined as follows: A string \(x\) is lexicographically smaller than a string \(y\) if either there exists an index \(m\) such that the first \(m-1\) characters of \(x\) and \(y\) are identical but \(x_m < y_m\), or if \(x\) is a proper prefix of \(y\).
inputFormat
The input consists of the following:
- A line with two integers \(n\) and \(k\) (with \(1 \le n \le \dots\) and \(1 \le k \le 26\)), where \(n\) is the number of crystals and \(k\) is the number of types.
- A line containing a string of length \(n\) made up of the first \(k\) lowercase letters representing the crystal sequence.
- \(k\) lines follow, each containing a string of \(k\) characters (each either '0' or '1'), representing the table \(A\). The \(j\)th character in the \(i\)th line corresponds to \(A_{i,j}\), where rows and columns are 0-indexed with 'a' corresponding to index 0, 'b' to index 1, etc.
outputFormat
Output a single line containing the lexicographically smallest string that can be obtained after performing a sequence of allowed removal operations.
sample
3 3
bac
010
101
010
b
</p>