fun main() { val testCase = readln().toInt() for (case in 1 .. testCase) { val wordsCount = readln().toInt() val words = readln().split(' ') when(val result = solve(wordsCount, words)) { null -> println("Case #$case: IMPOSSIBLE") else -> { println("Case #$case: POSSIBLE") println(result.joinToString(" ")) } } } } fun solve(wordsCount: Int, words: List): List? { val result = mutableListOf(words.first().toList().sorted().joinToString("")) for (i in 1 until wordsCount) { val next = words[i] result.add(next.makeGe(result.last()) ?: return null) } return result } fun String.nextGreater(): String? { var last = lastIndex - 1 while (last >= 0 && this[last] >= this[last + 1]) { --last } if (last < 0) return null var next = last + 1 while (next < length && this[last] < this[next]) { ++next } --next val result = this.toCharArray() result[next] = this[last] result[last] = this[next] return result.take(last + 1).joinToString("") + result.drop(last + 1).reversed().joinToString("") } fun String.makeGe(target: String): String? { val count = IntArray(26){0} for (c in this){ count[c - 'A'] += 1 } val result = StringBuilder() var last = 0 while (last < target.length) { val c = target[last] - 'A' if (count[c] == 0) break result.append(target[last]) --count[c] ++last } if (last == target.length) { for (i in count.indices) { while (count[i] > 0) { --count[i] result.append('A' + i) } } return result.toString() }else { val c = target[last] - 'A' return when(val next = (c until 26).find { count[it] > 0 }) { null -> { for (i in count.indices.reversed()) { while (count[i] > 0) { --count[i] result.append('A' + i) } } result.toString().nextGreater() } else -> { result.append('A' + next) --count[next] for (i in count.indices) { while(count[i] > 0) { --count[i] result.append('A' + i) } } result.toString() } } } }