problems / 257

Chaining the Station Codes

medium graphs eulerian-path dfs strings 1000 ms · 256 MB

Chaining the Station Codes

A railway gives each of its stations a code made of lowercase letters. For an anniversary tour it wants to announce all n codes in a single chain: every code is used exactly once, and each code after the first must start with the letter the previous code ends with. Several stations may share the same code; they are still different entries and each must appear once.

The codes are numbered 1 to n in input order. A chain is written as the sequence of these numbers. Among all valid chains, print the lexicographically smallest one: compare two chains by the first position where they differ, and the one with the smaller number there is smaller. If no valid chain exists, print IMPOSSIBLE.

Input

The first line contains n (1 ≤ n ≤ 2·10^5), the number of codes.

Each of the next n lines contains one code: a string of 1 to 10 lowercase English letters. A one-letter code starts and ends with the same letter.

Output

Print n distinct integers from 1 to n separated by spaces: the lexicographically smallest valid chain. If there is none, print IMPOSSIBLE.

Notes

In the first example, dock must come first, since nothing ends with d. After it, taking knot (code 2) would leave kiln and nook unreachable, because no code starts with t. So the chain continues with kiln, nook, and only then knot: 1 3 4 2.

In the second example, tea appears twice, as codes 1 and 4. The chain 1 2 4 3 reads tea at tea ant.

In the third example, pop can only be followed by a code starting with p and tat by one starting with t, so the two codes cannot be joined.

Example 1

Input

4
dock
knot
kiln
nook

Output

1 3 4 2

Example 2

Input

4
tea
at
ant
tea

Output

1 2 4 3

Example 3

Input

2
pop
tat

Output

IMPOSSIBLE

Hints · reveal one at a time if you're stuck

Hint 1

Only the first and last letter of each code matter. Try drawing the 26 letters as points and each code as an arrow from its first letter to its last.

Hint 2

A chain is then a walk that uses every arrow exactly once. Which letter must it start from, judging by how many arrows enter and leave each letter? And when every letter is balanced, which code can always come first?

Hint 3

You are looking for an Eulerian path in a directed multigraph. Hierholzer's algorithm builds one in linear time, and if every letter tries its outgoing codes in increasing index order, the path it builds is the smallest.

report an issue Prefer your own editor? sooks prep 257 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.