시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율
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
W3sicHJvYmxlbV9pZCI6IjI5MzIiLCJwcm9ibGVtX2xhbmciOiIwIiwidGl0bGUiOiJcdWQ0NWMgXHVkNjhjXHVjODA0IiwiZGVzY3JpcHRpb24iOiI8cD5cdWMwYzFcdWFkZmNcdWM3Nz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