Under construction

Still being built. Things may change

Cyclic Shift and Minimal Inversions

Time limit2sMemory limit512 MB

Summary
Maintain a permutation under subarray cyclic-shift updates, and after each update report the smallest shift k whose cyclic rotation has the fewest inversions.
Level

Hard8 of 10

Topics
Array, Dynamic programming, Greedy, Math
Solved
No attempts yet

Problem

A cyclic shift of a sequence ss by kk (0≤k<∣s∣0 \leq k < |s|) positions is the following sequence sksk+1…s∣s∣−1s0s1…sk−1s_{k} s_{k+1} \ldots s_{|s|-1} s_0 s_1 \ldots s_{k-1}. Note that 0-indexing is used. For example, cyclic shift by 0 positions is equal to the original sequence.

There is a permutation which is initially equal to the identity permutation (0,1,…,n−10, 1, \ldots, n-1).

Process a number of the following queries. Replace a subarray of the permutation by its cyclic shift by some number of positions. Formally you are given l,r,kl, r, k, such that 0≤l<r≤n0\leq l < r \leq n, 1≤k<r−l1 \leq k < r - l and replace the subarray between indices ll and rr (a half-interval, ll-th element is included, rr-th is not) by its cyclic shift by kk positions. For example, applying this operation to the permutation [1,0,3,4,2][1, 0, 3, 4, 2] with parameters l=1,r=4,k=1l = 1, r = 4, k = 1 results in a permutation [1,3,4,0,2][1, 3, 4, 0, 2].

After each query find the cyclic shift of the permutation which contains the minimal number of inversions.

The changes of the permutation persist and are not reverted between queries.

Input

The first line contains two integers nn and qq (2≤n≤105,1≤q≤1052 \leq n \leq 10^5, 1 \leq q \leq 10^5), length of the permutation and the number of queries, respectively.

qq lines follow. ii-th of them contains three integers li,ri,kil_i, r_i, k_i (0≤li<ri≤n,1≤ki<ri−li0 \leq l_i < r_i \leq n, 1 \leq k_i < r_i - l_i), parameters of the ii-th query.

Output

Print qq lines. ii-th of them should contain an integer kk (0≤k<n0 \leq k < n), such that after the first ii queries cyclic shift of the permutation by kk positions contains the minimal number of inversions among cyclic shifts. If there are multiple possible kk print the smallest one.

Hint

In the first example after the modification the permutation is [0,4,5,6,1,2,3,7][0, 4, 5, 6, 1, 2, 3, 7]. Its cyclic shift with the minimal number of inversions is [1,2,3,7,0,4,5,6][1, 2, 3, 7, 0, 4, 5, 6].

Examples2

  1. Example 1

    Input
    8 1
    1 7 3
    
    Expected output
    4
    
  2. Example 2

    Input
    7 5
    1 7 2
    0 5 1
    2 6 3
    0 5 4
    0 7 5
    
    Expected output
    5
    4
    5
    3
    0