Hide

Problem G
Easy As CAB

We all know how to alphabetize a list of distinct words when the alphabet is known. If one word is a prefix of another, the shorter word always comes first. For any other pair of words, the order is determined by the first position where their letters differ; the letters at this position define the lexicographical order.

Reverse Problem: Given an ordered list of words, can you determine the lexicographic order of the alphabet? Suppose an alphabet exists such that the following list of Unicode words is in lexicographical order:

ÇÅB
ÇDÅ
ÇÇÇ
BÅDÇÅ

It is clear that Ç comes before B, because ÇÅB precedes BÅDÇÅ. Similarly:

  • comes before D, because ÇÅB < ÇDÅ.

  • comes before Ç, because ÇÅB < ÇÇÇ.

  • D comes before Ç, because ÇDÅ < ÇÇÇ.

The only possible ordering of the four alphabet characters is ÅDÇB.

Some lists may contain inconsistencies, making any alphabet ordering impossible. For example:

ÅBÇ
BÇÅ
ÇÅB
ÅÇÅ

Here, must come before B, since ÅBÇ < BÇÅ, but B must also come before , since BÇÅ < ÅÇÅ. This is a contradiction.

Some lists may not provide enough information to derive a unique alphabet order. For example:

DÉÅ
ÇFB

Here, D comes before Ç, but the relative order of the other letters is unknown. Hence, the alphabet ordering is not uniquely determined.

Input

  • The first line contains an integer $N$ $(0 < N \le 1000)$ — the number of UTF-8 encoded strings in the list.

  • Each of the next $N$ lines contains a single, nonempty, valid UTF-8 string (without grapheme clusters) of length at most 2000 bytes.

  • All strings are distinct.

Output

  • If the input is consistent with a unique alphabet ordering, output a string describing that order.

  • If the input is inconsistent with any ordering, output IMPOSSIBLE.

  • If the input is consistent with multiple possible orderings, output AMBIGUOUS.

Sample Input 1 Sample Output 1
4
ÇÅB
ÇDÅ
ÇÇÇ
BÅDÇÅ
ÅDÇB
Sample Input 2 Sample Output 2
4
ÅBÇ
BÇÅ
ÇÅB
ÅÇÅ
IMPOSSIBLE
Sample Input 3 Sample Output 3
2
DÉÅ
ÇFB
AMBIGUOUS
Sample Input 4 Sample Output 4
5
ebbce
dbe
adcd
bc
cd
edabc

Please log in to submit a solution to this problem

Log in