Shuffle

Time limit1sMemory limit128 MB

Summary
After applying m shuffles to an ordered deck of n cards, count how many cards numbered r or less fall in positions p through q. n is up to 1e9, so the huge deck must be tracked implicitly.
Level

Medium7 of 10

Topics
Combinatorics, Math, Implementation, Intervals
Solved
No attempts yet

Problem

There are nn cards numbered 11 through nn. Initially they are stacked in order so that the top card is number 11, the second from the top is number 22, …, and the bottom card is number nn.

Initial state of the deck

The deck is rearranged by an operation called shuffle(x,y)(x, y), where xx and yy are integers with 1≤x<y<n1 \le x < y < n.

  • shuffle(x,y)(x, y)
    • Split the nn cards into three piles: pile AA consisting of the top xx cards, pile BB consisting of the cards from position x+1x+1 to yy, and pile CC consisting of the cards from position y+1y+1 to nn. Then place pile BB on top of pile AA, and place pile CC on top of that.

For example, applying shuffle(3,5)(3, 5) to 99 ordered cards makes the numbers, from top to bottom, 6,7,8,9,4,5,1,2,36, 7, 8, 9, 4, 5, 1, 2, 3.

Example of shuffle(3, 5)

Starting from the initial deck, perform mm shuffles shuffle(x1,y1)(x_1, y_1), shuffle(x2,y2)(x_2, y_2), …, shuffle(xm,ym)(x_m, y_m) in order. Write a program that, in the resulting deck, counts how many cards numbered rr or less lie among the cards from position pp to position qq counted from the top.

Input

The input consists of m+3m+3 lines.

  • Line 11: the number of cards nn (3≤n≤1093 \le n \le 10^9).
  • Line 22: the number of shuffles mm (1≤m≤50001 \le m \le 5000).
  • Line 33: three integers p,q,rp, q, r (1≤p≤q≤n1 \le p \le q \le n, 1≤r≤n1 \le r \le n).
  • Line i+3i+3 (for 1≤i≤m1 \le i \le m): two integers xix_i and yiy_i (1≤xi<yi<n1 \le x_i < y_i < n) separated by a space.

Output

Output the number of cards numbered rr or less among the cards from position pp to position qq (counted from the top) in the deck after the mm shuffles.

Notes

Applying shuffle(3,5)(3, 5) to a deck of 99 cards makes the cards, from top to bottom, 6,7,8,9,4,5,1,2,36, 7, 8, 9, 4, 5, 1, 2, 3. Among positions 33 through 77 from the top, the cards numbered 44 or less are number 44 and number 11 — 22 cards.

Applying shuffle(3,8)(3, 8), shuffle(2,5)(2, 5), shuffle(6,10)(6, 10) in order to a deck of 1212 cards makes the cards, from top to bottom, 9,10,3,11,12,4,5,6,7,8,1,29, 10, 3, 11, 12, 4, 5, 6, 7, 8, 1, 2. Among positions 33 through 88 from the top, there are 33 cards numbered 55 or less.

Examples2

  1. Example 1

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

    Input
    12
    3
    3 8 5
    3 8
    2 5
    6 10
    
    Expected output
    3