Under construction

Still being built. Things may change

Coins

Interview

Time limit2sMemory limit1024 MB

Summary
Rearrange an N x N grid of copper and silver coins so all copper sits in a staircase region at the top left, using the fewest swaps.
Level

Medium5 of 10

Topics
Dynamic programming, Matrix, Prefix sum
Solved
No attempts yet

Problem

There are coins placed on squares of a N×NN \times N grid board where NN is even. There is one coin in each square. Exactly half of the coins are silver ones, the other half are copper.

The coins are placed properly if all the copper coins are in the upper left part of the board and silver coins are placed on the lower right part of the board. To be precise, if the edge of a square is a separator between different types of coins, the copper coin is either to the left or above the silver coin.

Proper placementImproper placement

Figure 1: The coins are placed properly if there are no placements as shown on the right. Black circles represent copper coins, white circles represent silver ones.

You are given a set of coins placed improperly on the board. Rearrange them to get a proper placement by switching as few pairs of coins as possible.

Input

The first line contains four integers TT, NN, K1K_1, K2K_2.

  • TT is the number of the test.
  • NN is the board size.
  • K1K_1 and K2K_2 are values that define grading (see the Grading section).

Each of the remaining NN lines contains NN integers. They describe the initial coin placement on the board. Each integer is either 0 (copper coin) or 1 (silver coin).

Output

Output the board with a proper placement of coins in the same format as the input, as an N×NN \times N board. Exactly half of the integers are 0 (copper coin), and the other half are 1.

Examples1

  1. Example 1

    Input
    0 4 1 5
    0 0 1 0
    0 0 0 1
    0 1 1 1
    1 1 0 1
    
    Expected output
    0 0 1 1
    0 0 1 1
    0 0 1 1
    0 0 1 1