This page is still under construction.

Parts of this page are still being built. What you see may change.

Photo

Interview

Time limit1sMemory limit128 MB

Summary
Given N cows in a line and K unfriendly pairs that cannot share a photo, find the minimum number of consecutive-range photos covering every cow.
Level

Medium7 of 10

Topics
Greedy, Intervals, Two pointers, Sorting
Solved
No attempts yet

Problem

Farmer John wants to take photos of his NN cows (2≤N≤1092 \le N \le 10^9), which are standing in a line and conveniently numbered 1…N1 \ldots N from left to right. Each photograph can capture a consecutive range of cows from the lineup, and Farmer John wants to make sure that each cow appears in at least one photo.

Unfortunately, there are KK unfriendly pairs of cows (1≤K≤10001 \le K \le 1000) that each refuse to be in the same photograph. Given the locations of these unfriendly pairs, determine the minimum number of photos Farmer John needs to take.

Input

  • Line 1: Two space-separated integers, NN and KK.
  • Lines 2…K+12 \ldots K+1: Line i+1i+1 contains two integers, AiA_i and BiB_i, stating that the cows in positions AiA_i and BiB_i are unfriendly and therefore cannot be in the same photograph (1≤Ai,Bi≤N1 \le A_i, B_i \le N, Ai≠BiA_i \ne B_i).

Output

  • Line 1: A single integer specifying the minimum number of photos Farmer John needs to take.

Hint

When N=7N = 7 and the unfriendly pairs are (1,3)(1, 3), (2,4)(2, 4), (5,6)(5, 6), Farmer John can take 3 photos:

  • One ranging from 11 to 22.
  • One ranging from 33 to 55.
  • One ranging from 66 to 77.

Examples1

  1. Example 1

    Input
    7 3
    1 3
    2 4
    5 6
    
    Expected output
    3