Online Shopping
Time limit1sMemory limit128 MB
Reorder rows and columns of a matrix so the resulting row-by-row string of prices is lexicographically smallest.
- Level
Medium7 of 10
- Topics
- Brute force, Sorting, Greedy, Implementation
- Solved
- No attempts yet
Problem
As online shopping grows, services that let you compare the prices of many stores at a glance become popular. To show the cheapest offer for a product quickly, such a service wants to lay out its price table as tidily as possible.
You are given one price table. It has one row per product, for a total of rows, and one column per online shop, for a total of columns. The cell in row and column is the price of product at shop .
You may reorder the products (the rows) and the shops (the columns) independently and in any way you like. Once an arrangement is fixed, its table string is obtained by reading the table row by row: for each product in order, list that product's prices at every shop in order, separating all values by single spaces.
Among all arrangements of the rows and columns, output the one whose table string is smallest. Two table strings are compared value by value: at the first position where they differ, the one with the smaller price (an integer number of cents) is the smaller table string.
Input
The first line contains a single integer , the number of test cases.
Each of the next lines describes one test case. A line begins with two integers and (), the number of products and the number of shops. They are followed by the prices of the table's initial arrangement, given as its table string: for each product in order, that product's prices, one per shop. Every price is an integer number of cents with .
Output
For each test case, print a line Scenario #i:, where is the test case number starting from . On the next line, print the table string of the optimal reordering of the products and shops. Separate two consecutive test cases with a blank line.