Algorithm


B. Young Photographer
time limit per test
2 seconds
memory limit per test
64 megabytes
input
standard input
output
standard output

Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second — from a2 to b2

What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.

Input

The first line of the input file contains integers n and x0 (1 ≤ n ≤ 1000 ≤ x0 ≤ 1000). The following n lines contain pairs of integers ai, bi (0 ≤ ai, bi ≤ 1000ai ≠ bi).

Output

Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.

Examples
input
Copy
3 3
0 7
14 2
4 6
output
Copy
1



 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

#include <cstdio>

int main(){

    int n, x0; scanf("%d %d\n", &n, &x0);
    int m(0), M(1001);

    while(n--){
        int a, b; scanf("%d %d\n", &a, &b);
        if(a > b){int temp(a); a = b; b = temp;}
        if(b < M){M = b;}
        if(a > m){m = a;}
    }

    if(m > M){puts("-1");}
    else{
        int ans = 1001;
        if(m <= x0 && x0 <= M){ans = 0;}
        if(x0 < m && ans > m - x0){ans = m - x0;}
        if(x0 > M && ans > x0 - M){ans = x0 - M;}
        printf("%d\n", ans);
    }

    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
3 3
0 7
14 2
4 6

Output

x
+
cmd
1
Advertisements

Demonstration


Codeforces Solution-B. Young Photographer-Solution in C, C++, Java, Python

Previous
Codeforces solution 1080-B-B. Margarite and the best present codeforces solution
Next
CodeChef solution DETSCORE - Determine the Score CodeChef solution C,C+