#B3675. Row Disorder Sorting
Row Disorder Sorting
Row Disorder Sorting
After a military training session, the drill instructor arranged all students in a matrix of n rows and m columns. For the row‐by‐row drill, the arm raising height and the leg kicking height for the j-th student in the i-th row are given by ai,j and bi,j respectively.
The disorder of the i-th row is defined as the sum of the variances of the arm heights and the leg heights. Formally, the disorder of row i is:
$$ D_i = \frac{1}{m}\sum_{j=1}^{m}\Bigg(a_{i,j}-\frac{\sum_{k=1}^{m}{a_{i,k}}}{m}\Bigg)^2 + \frac{1}{m}\sum_{j=1}^{m}\Bigg(b_{i,j}-\frac{\sum_{k=1}^{m}{b_{i,k}}}{m}\Bigg)^2 $$The instructor wants to rearrange the rows by performing a series of swaps of two rows at a time (each swap is immediately effective) so that in the final arrangement, the disorders of the rows are in non-decreasing order from row 1 to row n. If two rows have equal disorder, their order can be arbitrary.
Note: When a swap is performed (for example between row 1 and row 3), the row originally in position 1 becomes the new row in that position and vice versa. In other words, row indices refer to the current positions at the time of the swap.
Your task is to output one valid sequence of swaps which results in a final arrangement with non-decreasing disorder values.
Example:
Current Row Number | Initial Row Number |
---|---|
1 | 1 |
2 | 2 |
3 | 3 |
If the following swaps are performed:
- Swap row 1 and row 2.
- Swap row 2 and row 3.
Then the row order changes as follows:
Current Row Number | Initial Row Number |
---|---|
1 | 2 |
2 | 1 |
3 | 3 |
After these swaps, the disorders of the rows (calculated from the original matrix data) will be in non-decreasing order.
inputFormat
The first line contains two integers n and m (1 ≤ n, m ≤ 1000), representing the number of rows and columns respectively.
The next n lines each contain m integers. The i-th line represents the arm heights ai,1, ai,2, ..., ai,m for row i.
The following n lines each contain m integers. The i-th of these lines represents the leg heights bi,1, bi,2, ..., bi,m for row i.
outputFormat
First, output an integer t on a single line, representing the number of swaps performed.
Then, output t lines, each with two integers i and j (1 ≤ i, j ≤ n), representing that the row currently at position i is swapped with the row currently at position j. Each swap is performed on the current arrangement.
A valid sequence of swaps that arranges the rows in non-decreasing order of their disorder value is acceptable. If the rows are already in non-decreasing order, output 0.
sample
3 2
1 2
2 1
3 3
4 4
2 2
1 1
2
2 3
1 2
</p>