시간 제한메모리 제한제출정답맞힌 사람정답 비율
1 초 128 MB237637.500%

문제

상근이는 N×N 표를 만들었다. 표에는 1부터 N2까지의 수가 행 우선 순서(row-major order)에 따라 쓰여져 있다. 표가 수행할 수 있는 연산은 아래와 같이 두 가지이다.

  1. 행을 회전시킨다 - 한 행을 골라 오른쪽으로 한 칸 회전시킨다. 마지막 열에 있던 수가 가장 첫 열에 오게 된다.
  2. 열을 회전시킨다 - 한 열을 골라 아래로 한 칸 회전시킨다. 마지막 행에 있던 수가 갖아 첫 행에 오게 된다.

상근이는 수 X를 (R,C)로 이동시키려고 한다. 이때, 상근이는 다음과 같은 과정을 거쳐서 수를 찾는다.

  • X의 위치가 C열이 될 때 까지, X가 있는 행을 회전 시킨다.
  • X의 위치가 R행이 될 때 까지, X가 있는 열을 회전시킨다.

아래 그림은 6을 (3,4)에 이동시키는 방법이다.

상근이는 숫자 K개를 이동시키려고 한다. 한 숫자를 이동시키고 난 후에, 바로 그 다음 숫자를 이동시키며, 다음 숫자를 이동시킬 때, 표에 들어있는 수를 처음 상태로 되돌리지 않는다. 숫자 K개를 이동시키는데 필요한 회전의 수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 표의 크기 N(2 ≤ N ≤ 10000)과 이동시키려고 하는 숫자의 수 K(1 ≤ K ≤ 1000)이 주어진다.

다음 K개 줄에는 이동시키려고 하는 숫자 X와 위치 R, C가 주어진다. (1 ≤ X ≤ N2, 1 ≤ R,C ≤ N)

항상 입력으로 주어진 순서대로 하나씩 이동시켜야 한다.

출력

총 K개 줄에 각각의 숫자를 이동시키는데 필요한 회전의 수를 출력한다.

예제 입력 1

4 1
6 3 4

예제 출력 1

3

예제 입력 2

4 2
6 3 4
6 2 2

예제 출력 2

3
5

예제 입력 3

5 3
1 2 2
2 2 2
12 5 5

예제 출력 3

2
5
3
W3sicHJvYmxlbV9pZCI6IjI5MzIiLCJwcm9ibGVtX2xhbmciOiIwIiwidGl0bGUiOiJcdWQ0NWMgXHVkNjhjXH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