Puzzle
Time limit1sMemory limit128 MB
Build the longest string over the first n capital letters that avoids all forbidden substrings, or print No when no maximum exists.
- Level
Hard9 of 10
- Topics
- String matching, Trie, Graph, Dynamic programming
- Solved
- No attempts yet
Problem
Jisung is the student council president of the Computer Engineering department at ACM University. The department's annual festival is coming up, and Jisung is preparing events for it. Because he enjoys creating and solving puzzles, he decides to design an interesting string puzzle for the festival.
The puzzle works as follows.
- Each player is given an integer and may use only the first capital letters of the alphabet. For example, when the usable letters are A, B, C, and D.
- Each player is also given forbidden strings. No forbidden string is a substring of another forbidden string. The winner is the player who builds the longest string that contains none of the forbidden strings as a substring.
- If such a longest string does not exist, that is, if valid strings can be made arbitrarily long, or if no non-empty valid string can be made at all, the answer is
No.
For example, with the usable letters are A and B. If the forbidden strings are {AAA, AB, BA, BB}, the longest string that avoids all four as substrings is AA. But if the forbidden strings are {AAA, BBB, ABAB, BBAA}, no longest string exists: arbitrarily long repetitions such as ABAABAABA... never contain a forbidden substring, so the answer is No.
Input
The first line contains the number of test cases . Each test case begins with a line containing two integers () and (), the number of usable letters and the number of forbidden strings. The next lines each contain one forbidden string. Every forbidden string has length at most , consists only of the first capital letters, and no forbidden string is a substring of another.
Output
For each test case, print exactly one line. If a longest valid string exists, print it; otherwise print No. A valid string is one that contains none of the forbidden strings as a substring. Print No when valid strings can be arbitrarily long, or when the only valid string is the empty string (no non-empty valid string exists). When several valid strings share the maximum length, print the lexicographically largest one.