Official

C - Reorder Cards Editorial by en_translator


Since the operation on rows and operations on columns does not interfere each other. Therefore, we can consider columns and rows independently. Here, we explain how to find the resulting row index, but the column index can be found in the similar way.

First, an operation does not change the relative positions of the cards (like which card are above another). Moreover, after all the operations have completed, every row and column will have at least one card with a number written on it. Therefore, after the operations ended, the uppermost card with a number written on it will be in the first row, the second upper most one in the second row, … and so on.

Therefore, the original problem boils down to this problem: “minimize the values of \(A_i\) while preserving the order.” For example, given \(O(N\log N)\), it requires to transform it to \((1,4,4,3,4,1,2)\).

This operation is nothing more than “coordinate compression.” Thus the problem has been solved in a total of \(O(N\log N)\) time. For a specific explanation on how to implement it, search it on your on.

Sample code (Python)

H,W,N=map(int,input().split())
X,Y=[],[]
for i in range(N):
  x,y=map(int,input().split())
  X.append(x)
  Y.append(y)

Xdict = {x:i+1 for i,x in enumerate(sorted(list(set(X))))}
Ydict = {y:i+1 for i,y in enumerate(sorted(list(set(Y))))}

for i in range(N):
  print(Xdict[X[i]], Ydict[Y[i]])

posted:
last update: