Cups and Marbles

Time limit4sMemory limit256 MB

Summary
After m range-sort spells (ascending or descending) on a permutation, report the marble in the middle cup.
Level

Hard8 of 10

Topics
Binary search, Sorting, Implementation, Segment tree
Solved
No attempts yet

Problem

Hongjun and Myungwoo like to play. Bored one day, Hongjun invented the following game.

There are nn cups and nn marbles, each numbered from 1 to nn. Hongjun put one marble into every cup and lined the cups up in order of their numbers. At the start, cup ii holds marble aia_i.

Hongjun casts a spell mm times. One cast takes every cup lying between two chosen cups, sorts the marbles in those cups by number in ascending or descending order, and puts them back one per cup, starting from the lowest numbered cup.

Once every spell is done, Hongjun asks Myungwoo which marble sits in cup n+12\frac{n+1}{2}. nn is always odd.

Consider n=5n = 5, m=2m = 2 and a=[5,1,4,2,3]a = [5, 1, 4, 2, 3]. If the first spell sorts the marbles in cups 1 through 4 in ascending order, aa becomes [1,2,4,5,3][1, 2, 4, 5, 3]. If the second spell sorts the marbles in cups 2 through 5 in descending order, aa becomes [1,5,4,3,2][1, 5, 4, 3, 2]. Cup 3 is left holding marble 4.

Help Myungwoo and write a program that answers Hongjun's question.

Input

The first line contains two integers nn and mm. (1≤n≤99,9991 \le n \le 99{,}999, 0≤m≤100,0000 \le m \le 100{,}000) nn is odd.

The second line contains nn integers a1,a2,…,ana_1, a_2, \dots, a_n. (1≤ai≤n1 \le a_i \le n) aa is a permutation of 11 through nn.

Each of the next mm lines holds one spell, in the order Hongjun casts them. A line contains two integers lil_i and rir_i. (1≤li,ri≤n1 \le l_i, r_i \le n) If li<ril_i < r_i, the marbles in cups lil_i through rir_i are sorted by number in ascending order. If li≥ril_i \ge r_i, the marbles in cups rir_i through lil_i are sorted by number in descending order.

Output

Print the number of the marble in cup n+12\frac{n+1}{2} after all mm spells.

Examples5

  1. Example 1

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

    Input
    1 0
    1
    
    Expected output
    1
    
  3. Example 3

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

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

    Input
    11 3
    11 10 9 8 7 6 5 4 3 2 1
    1 5
    11 6
    4 8
    
    Expected output
    6