CANDYSTRIPE2
We have (once again*) chocolates, numbered from to , wrapped and placed in a row like a filmstrip. Some of them have bitter chocolate, and some have sweet chocolate. Because our brother has a strong aversion to bitter chocolate, we placed a special order at the patisserie requesting the film to have few bitter chocolates and many sweet ones.
As proof that they fulfilled our request, the confectionery enumerates a set of segments of the film, each described by two numbers and , indicating the chocolates from position to (inclusive). They assure us that each of these segments contains exactly one bitter chocolate.
If the assurances of the patisserie are true, find out how many bitter chocolates can be at most in the film.
Input:
The first line of the input will contain two positive integers and , separated by a space: the size of the film and the number of segments enumerated by the patisserie. Each of the next lines corresponds to a numbered segment and contains two integers, and , separated by a space.
Output:
The output should contain a single line with exactly one integer: the maximum number of bitter chocolates that can exist in the film, if the patisserie's guarantees are true. If there is no consistent answer according to the guarantees of the patisserie, the output should be the number .
Constraints:
- και
- Time Limit: sec.
- Memory Limit: MB.
- For test cases with a total value of , it will be and .
- For test cases with a total value of , it will be and .
- For test cases with a total value of , it will be and .
- For test cases with a total value of , it will be .
Examples of Input - Ouput:
1st
input:
5 3
3 4
1 4
2 5
output:
1
2nd
input:
6 2
2 4
3 5
output:
4
3d
input:
4 3
1 4
2 2
3 3
output:
-1
Explanation of the examples:
In the first example, there can only be one bitter chocolate, either at position or position . In the second example, there can be four bitter chocolates at positions , , , and . In the third example, the last two segments guarantee that there are bitter chocolates at positions and . However, the first segment guarantees that there is only one bitter chocolate between positions and . These guarantees cannot all be true simultaneously.
- The solution to this problem is not related to yesterday's candystripe problem- only the story has similarities.
Comments