atcoder#ARC141E. [ARC141E] Sliding Edge on Torus

[ARC141E] Sliding Edge on Torus

Score : 700700 points

Problem Statement

There is an undirected graph with N2N^2 vertices. Initially, it has no edges. For each pair of integers (i, j)(i,\ j) such that 0i, j<N0 \leq i,\ j < N, the graph has a corresponding vertex called (i, j)(i,\ j).

You will get QQ queries, which should be processed in order. The ii-th query, which gives you four integers ai, bi, ci, dia_i,\ b_i,\ c_i,\ d_i, is as follows.

  • For each kk (0k<N)(0 \leq k < N), add an edge between two vertices ((ai+k)modN, (bi+k)modN)((a_i+k) \bmod N,\ (b_i+k) \bmod N) and ((ci+k)modN, (di+k)modN)((c_i+k) \bmod N,\ (d_i+k) \bmod N). Then, print the current number of connected components in the graph.

Constraints

  • 2N2×1052 \leq N \leq 2 \times 10^5
  • 1Q2×1051 \leq Q \leq 2 \times 10^5
  • 0ai, bi, ci, di<N0 \leq a_i,\ b_i,\ c_i,\ d_i < N
  • (ai, bi)(ci, di)(a_i,\ b_i) \neq (c_i,\ d_i)
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN QQ

a1a_1 b1b_1 c1c_1 d1d_1

a2a_2 b2b_2 c2c_2 d2d_2

\vdots

aQa_Q bQb_Q cQc_Q dQd_Q

Output

Print QQ lines. The ii-th line should contain the number of connected components in the graph at the ii-th query.

3 3
0 0 1 2
2 0 0 0
1 1 2 2
6
4
4

The first query adds an edge between (0, 0), (1, 2)(0,\ 0),\ (1,\ 2), between (1, 1), (2, 0)(1,\ 1),\ (2,\ 0), and between (2, 2), (0, 1)(2,\ 2),\ (0,\ 1), changing the number of connected components from 99 to 66.

4 3
0 0 2 2
2 3 1 2
1 1 3 3
14
11
11

The graph after queries may not be simple.

6 5
0 0 1 1
1 2 3 4
1 1 5 3
2 0 1 5
5 0 3 3
31
27
21
21
19