#K64097. Rearrange Strings Without Substrings

    ID: 31899 Type: Default 1000ms 256MiB

Rearrange Strings Without Substrings

Rearrange Strings Without Substrings

You are given a list of strings. Your task is to rearrange the strings in such a way that no string is a substring of any other string that comes after it. The rearrangement should be done in increasing order of string length. If it is impossible to arrange the strings to satisfy the condition, output NOT POSSIBLE.

Note: The order among strings of the same length should be maintained as in the original input (i.e., stable order). For each test case, you must process the list of words and determine the appropriate output.

Example:

Input:
1
4
bat cat batman catman

Output: NOT POSSIBLE

</p>

In the example above, "bat" is a substring of "batman" and "cat" is a substring of "catman", hence the list cannot be rearranged to satisfy the condition.

inputFormat

The input is read from standard input (stdin) and consists of multiple test cases. The first line contains an integer T indicating the number of test cases. Each test case is described as follows:

  • The first line of each test case contains an integer n, the number of strings.
  • The second line contains n words separated by spaces.

It is guaranteed that n ≥ 1.

outputFormat

For each test case, output one line to standard output (stdout):

  • If the list can be rearranged so that no string is a substring of any string that comes after it, print the rearranged words separated by a single space.
  • If it is not possible, print NOT POSSIBLE (without quotes).
## sample
1
4
bat cat batman catman
NOT POSSIBLE