Under construction

Still being built. Things may change

Find the Joker 2

Interview

Time limit1sMemory limit1024 MB

Summary
Given shuffles that rotate the deck by one card or point back to an earlier deck state, find the joker's final position starting from position 1.
Level

Medium4 of 10

Topics
Tree, Prefix sum, Math
Solved
No attempts yet

Problem

Suhyeon, a student at Chung-Ang University, learned card-cheating techniques. This time, after watching a magic video on YouTube, Suhyeon wants to copy the trick. Suhyeon places the joker on top of a card deck and shuffles the cards to send the joker to a desired position.

The deck has NN cards in total: N−1N-1 blank cards and 1 joker card. Call the top card card 1 and the bottom card card NN. In the initial deck, the joker is at position 1.

Suhyeon shuffles the cards MM times. There are 3 shuffle methods.

  • 1 xix_i: Move card NN on top of card 1. Repeat this xix_i times.
  • 2 yiy_i: Move card 1 under card NN. Repeat this yiy_i times.
  • 3 ziz_i: Change the deck state to the deck state after ziz_i shuffles from the initial state. If zi=0z_i = 0, change to the initial deck.
    • This does not turn back the deck's history. It only changes the deck state.

Input

The first line contains NN and MM, separated by a space.

The next MM lines describe the shuffles. Line ii describes the ii-th shuffle.

Output

Print the position of the joker from the top of the deck after all shuffles are finished.

Constraints

  • 1≤N,M≤100 0001 \le N, M \le 100\,000
  • 1≤xi,yi≤10181 \le x_i, y_i \le 10^{18}
  • 0≤zi<i0 \le z_i < i
  • 1≤i≤M1 \le i \le M
  • All input values are integers.

Examples4

  1. Example 1

    Input
    3 3
    3 0
    1 1
    2 2
    
    Expected output
    3
    
  2. Example 2

    Input
    4 5
    1 1
    1 1
    3 0
    1 1
    3 3
    
    Expected output
    1
    
  3. Example 3

    Input
    5 5
    1 4
    2 3
    3 1
    2 4
    1 3
    
    Expected output
    4
    
  4. Example 4

    Input
    9 2
    1 100000000000
    2 100000000001
    
    Expected output
    9