P2750 [IOI 2001 / USACO5.5] Two Five

Description

There is a strange language called the “Two Five” language. Each of its words consists of exactly one of each of the 25 letters from `A` to `Y`. However, not every permutation is a valid word in this language. A word is valid if, when its 25 letters are arranged into a $5\times 5$ matrix, every row and every column is strictly increasing. For example, the word `ACEPTBDHQUFJMRWGKNSXILOVY` forms the following matrix: ```plain ACEPT BDHQU FJMRW GKNSX ILOVY ``` Since every row and column is strictly increasing, it is a valid word. The word `YXWVUTSRQPONMLKJIHGFEDCBA` is clearly invalid. Because words are too long to store conveniently, we assign a code to each word. The coding method is as follows: read a matrix from left to right and then from top to bottom to obtain a word; then sort the words in lexicographic order. For example, the word `ABCDEFGHIJKLMNOPQRSTUVWXY` has code $1$, and the word `ABCDEFGHIJKLMNOPQRSUTVWXY` has code $2$. Now you need to write a program to convert between words and their codes.

Input Format

The first line contains a letter `N` or `W`. `N` means converting a code to a word, and `W` means converting a word to a code. If the first line is `N`, then the second line contains an integer representing the word’s code. If the first line is `W`, then the second line contains a valid word.

Output Format

Each line contains one integer or word.

Explanation/Hint

The statement is translated from NOCOW. USACO Training Section 5.5. Translated by ChatGPT 5