PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#CT0000128. Dòng xe vào bến (Bus Station Queue)

    ID: 1635 Loại: Thông thường 1000ms 256MiB Tried: 2 Đã chấp nhận: 0 Độ khó: 6 Đăng bởi: Nhãn>Greedy AlgorithmsGreedy proof techniquesData StructuresPriority queueSorting and SearchingSweep line techniqueBinary search on answer

Bài tập này chưa được xếp vào lộ trình.

Dòng xe vào bến (Bus Station Queue)

Bus Station Queue

Source: Bộ Giáo dục và Đào tạo

Version: Phuoc Hung OJ Extended

Problem Statement

Bus station XYZ has MM parking bays numbered 11 through MM. There are NN buses arriving in the fixed order 1,2,…,N1,2,\ldots,N. Bus ii accepts only a bay whose index belongs to the interval [ai,bi][a_i,b_i]. Each bay may serve at most one bus from this queue.

If the next bus cannot be assigned an acceptable unused bay, that bus and all later buses leave the station immediately. It is not permitted to skip a bus and serve subsequent ones.

Find the maximum number of consecutive buses from the beginning of the queue that can be served when the station may choose their assigned bays.

Input

  • The first line contains two integers M,NM,N.
  • Each of the next NN lines contains integers ai,bia_i,b_i, the range of bays accepted by bus ii.

Output

Print a single integer: the largest number of consecutive buses from the start that can be served.

Subtasks

  • Subtask 1 (25 points): 1≤M,N≤101\le M,N\le10; 1≤ai≤bi≤M1\le a_i\le b_i\le M for every 1≤i≤N1\le i\le N.
  • Subtask 2 (25 points): 1≤M,N≤3001\le M,N\le300; 1≤ai≤bi≤M1\le a_i\le b_i\le M for every 1≤i≤N1\le i\le N.
  • Subtask 3 (25 points): 1≤M,N≤500001\le M,N\le50000; ai=1a_i=1 and 1≤bi≤M1\le b_i\le M for every 1≤i≤N1\le i\le N.
  • Subtask 4 (25 points): 1≤M,N≤500001\le M,N\le50000; 1≤ai≤bi≤M1\le a_i\le b_i\le M for every 1≤i≤N1\le i\le N.

Examples

Example 1

Input

4 3
1 4
1 1
1 1

Output

2

Explanation: Assign bus 11 to bay 44 and bus 22 to bay 11. Bus 33 also requires bay 11, which is occupied, so three buses cannot be served; the answer is 22.

Example 2

Input

4 6
1 2
1 2
1 3
1 3
2 4
1 4

Output

3

Explanation: The first three buses can use bays 1,2,31,2,3. Bus 44 accepts only bays 1,2,31,2,3, which are all occupied; therefore the maximum prefix contains 33 buses.