시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율
1 초 128 MB 23 7 6 37.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

5 3
1 2 2
2 2 2
12 5 5

예제 출력 1

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