Suffix Array 3

Given a permutation built by moving and reversing intervals, count the strings whose suffix array equals it, modulo 1e9+7.

Medium7ArrayCombinatoricsMathImplementationNo attempts yetTime limit5sMemory limit512 MB

Problem

The ii-th suffix of a string SS is the suffix that starts at the ii-th character of SS. For example, if SS = "abcde", the 1st suffix is "abcde" and the 4th suffix is "de".

The suffix array of SS lists every suffix of SS in lexicographic order. Each entry of the array is a suffix number, and the sorting compares the suffixes those numbers refer to. For example, if SS = "abca", the suffix array is (4, 1, 2, 3).

Given a suffix array of length NN, write a program that counts the strings SS whose suffix array is that array.

Because NN can be very large, the suffix array SASA is built by operations. First initialize SA[i] = i, then apply MM operations in the given order. All positions are counted from 1.

  • 0 u v: move the uu-th through vv-th entries of SASA to the front of the array. After this operation the suffix array is SA[u], SA[u+1], ..., SA[v], SA[1], SA[2], ..., SA[u-1], SA[v+1], ..., SA[N].
  • 1 u v: reverse the uu-th through vv-th entries of SASA. After this operation the suffix array is SA[1], SA[2], ..., SA[u-1], SA[v], SA[v-1], ..., SA[u+1], SA[u], SA[v+1], ..., SA[N].

In this problem a string is an array of positive integers. The number of distinct integers in the string must equal the largest integer in the string. For example, (1, 2, 2) and (4, 5, 1, 2, 3) are valid strings, while (1, 1, 3) and (-1, 0, 1, 2) are not.

Input

The first line contains the length of the string NN (1N1091 \le N \le 10^9) and the number of operations MM (0M1050 \le M \le 10^5). Each of the next MM lines contains one operation that builds the suffix array. Every operation satisfies 1uvN1 \le u \le v \le N.

Output

Print the number of strings SS whose suffix array is the SASA given in the input, modulo 109+710^9+7.

Hint

In the first example the suffix array starts as (1, 2, 3, 4). After the first operation it is (1, 3, 2, 4), and after the second operation it is (2, 4, 1, 3). The possible strings are (2, 1, 2, 2), (2, 1, 3, 2), (3, 1, 3, 2), (3, 1, 4, 2).