Photo

Time limit1sMemory limit128 MB

Summary
Given intervals each containing exactly one marked point, find the maximum number of marked points, or -1 if no assignment is consistent.
Level

Hard8 of 10

Topics
Dynamic programming, Greedy, Intervals, Prefix sum
Solved
No attempts yet

Problem

Farmer John wants to assemble a panoramic photo of his NN cows (1≤N≤200,0001 \le N \le 200{,}000), conveniently numbered from 11 to NN. He took MM photos (1≤M≤100,0001 \le M \le 100{,}000); photo ii covers the contiguous range of cows from aia_i to bib_i inclusive (1≤ai≤bi≤N1 \le a_i \le b_i \le N). The photos need not cover every cow.

Afterward, Farmer John notices something curious: every photo he took contains exactly one spotted cow. He knows his herd has some spotted cows but has never counted them. Using the photos, determine the maximum possible number of spotted cows the herd could contain. If no way of marking cows as spotted is consistent with all of the photos, output −1-1.

Input

  • The first line contains two integers NN and MM.
  • Each of the next MM lines contains two integers aia_i and bib_i, the range of cows covered by photo ii.

Output

  • Print a single integer: the maximum possible number of spotted cows, or −1-1 if no valid assignment exists.

Notes

In the sample there are 55 cows and 33 photos, the first covering cows 11 through 44. The third photo covers cows 33 and 44, so exactly one of them must be spotted; marking either one also satisfies the first two photos, giving a maximum of 11 spotted cow.

Examples1

  1. Example 1

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