cho.sh
Notes
Loading...

Custom Table Sorter

Time limit

1s

Memory limit

128 MB

Problem

Websites often present data in tables. Different users may want to view the same rows in different orders.

A site listing hotels might sort by hotel name, location, star rating, or room rate. Write a support program for this kind of table-sorting feature.

Input

The input consists of several data sets.

Each data set has a heading line, a table section, and a sorter section. The heading line contains the title of the data set. A heading line containing only # terminates the input.

The table section contains at least 1 and at most 20 lines, and ends with a line containing only #. Each line contains between 1 and 10 comma-separated fields. All table lines have the same number of fields, and no field is empty. Each field is a string of length at most 20.

The sorter section contains several sorter lines. Each sorter line contains one or more comma-separated field sorters. A field sorter consists of a field number and a direction. Field numbers are distinct integers from 1 through the number of fields. The direction is A for ascending order or D for descending order.

The sorter section ends with a line containing only 0#.

Output

For each data set, first print its title. Then print one group of sorted table rows for each sorter line.

Each group contains the rows of the table in the requested order, with two leading spaces before every row. Put one blank line between groups within the same data set. Put one blank line between the outputs of consecutive data sets as well.

Sorting uses the first field sorter as the primary key. The second and later field sorters are used only for rows that tie on all previous sorter fields. If rows are still tied after all specified fields, they must remain in their original table order.

Constraints

A title has at most 25 characters and contains only letters and spaces.

Each field string contains only letters, digits, _, and *.