Problem:
Score : 500 points

Problem Statement

There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i.
Find the number of different values that the median of X_1, X_2, \cdots, X_N can take.

Notes

The median of X_1, X_2, \cdots, X_N is defined as follows. Let x_1, x_2, \cdots, x_N be the result of sorting X_1, X_2, \cdots, X_N in ascending order.

If N is odd, the median is x_{(N+1)/2};

if N is even, the median is (x_{N/2} + x_{N/2+1}) / 2.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

2
1 2
2 3

Sample Output 1

3

If X_1 = 1 and X_2 = 2, the median is \frac{3}{2};

if X_1 = 1 and X_2 = 3, the median is 2;

if X_1 = 2 and X_2 = 2, the median is 2;

if X_1 = 2 and X_2 = 3, the median is \frac{5}{2}.

Thus, the median can take three values: \frac{3}{2}, 2, and \frac{5}{2}.

Sample Input 2

3
100 100
10 10000
1 1000000000

Sample Output 2

9991

Solution in Rust (1.42.0) (judge verdict: Accepted)

#![allow(dead_code)]
use crate::misc::{arr, unzip};
use crate::scanner::Scanner;
fn main() {
    let mut scan = Scanner::new();
    let n = scan.read::<usize>();
    let (a, b) = unzip(&arr(n, || (scan.read::<i64>(), scan.read::<i64>())));
    let ret = if n % 2 == 1 {
        let left = calc_left(n / 2 + 1, &a);
        let right = calc_right(n / 2 + 1, &b);
        right - left + 1
    } else {
        let left_l = calc_left(n / 2, &a);
        let left_r = calc_right(n / 2 + 1, &b);
        let right_l = calc_left(n / 2 + 1, &a);
        let right_r = calc_right(n / 2, &b);
        let ll = left_l + right_l;
        let rr = left_r + right_r;
        rr - ll + 1
    };
    println!("{}", ret);
}
fn calc_left(half: usize, a: &[i64]) -> i64 {
    let n = a.len();
    let mut ok = 1i64 << 60;
    let mut ng = 0;
    while (ok - ng).abs() > 1 {
        let mid = (ok + ng) / 2;
        let mut sum = 0;
        for i in 0..n {
            sum += (a[i] <= mid) as usize;
        }
        if sum >= half {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    ok
}
fn calc_right(half: usize, b: &[i64]) -> i64 {
    let n = b.len();
    let mut ok = 0;
    let mut ng = 1i64 << 60;
    while (ok - ng).abs() > 1 {
        let mid = (ok + ng) / 2;
        let mut sum = 0;
        for i in 0..n {
            sum += (mid <= b[i]) as usize;
        }
        if sum >= half {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    ok
}
mod misc {
    use crate::tiny_num_traits::ZeroOne;
    use std::collections::{BTreeSet, HashMap};
    use std::ops::{Add, Div, Mul, Sub};
    pub const CONST_1E9_7: i64 = 1_000_000_007;
    pub fn arr<'a, S, T>(n: usize, mut f: S) -> Vec<T>
    where
        S: FnMut() -> T + 'a,
    {
        (0..n).map(|_| f()).collect::<Vec<T>>()
    }
    pub fn adjacent4(
        y: usize,
        x: usize,
        h: usize,
        w: usize,
    ) -> impl Iterator<Item = (usize, usize)> {
        const DYDX: [(isize, isize); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)];
        DYDX.iter().filter_map(move |&(dy, dx)| {
            let ny = y as isize + dy;
            let nx = x as isize + dx;
            if nx >= 0 && nx < w as isize && ny >= 0 && ny < h as isize {
                Some((ny as usize, nx as usize))
            } else {
                None
            }
        })
    }
    pub fn adjacent8(
        y: usize,
        x: usize,
        h: usize,
        w: usize,
    ) -> impl Iterator<Item = (usize, usize)> {
        const DYDX: [(isize, isize); 8] = [
            (-1, 0),
            (1, 0),
            (0, -1),
            (0, 1),
            (-1, -1),
            (-1, 1),
            (1, -1),
            (1, 1),
        ];
        DYDX.iter().filter_map(move |&(dy, dx)| {
            let ny = y as isize + dy;
            let nx = x as isize + dx;
            if nx >= 0 && nx < w as isize && ny >= 0 && ny < h as isize {
                Some((ny as usize, nx as usize))
            } else {
                None
            }
        })
    }
    pub fn run_length_encoding<T: Clone + PartialEq>(slice: &[T]) -> Vec<(i64, T)> {
        if slice.len() == 0 {
            return vec![];
        }
        let mut acc = vec![];
        let mut current = slice[0].clone();
        let mut cnt = 1i64;
        for i in 1..slice.len() {
            if current != slice[i] {
                acc.push((cnt, current));
                cnt = 0;
            }
            current = slice[i].clone();
            cnt += 1;
        }
        acc.push((cnt, current));
        acc
    }
    pub fn count<T: Eq + std::hash::Hash + Clone>(
        slice: &[T],
    ) -> std::collections::HashMap<T, usize> {
        let mut hmap = std::collections::HashMap::new();
        for item in slice {
            *hmap.entry(item.clone()).or_insert(0) += 1;
        }
        hmap
    }
    pub fn indices_by_elem<T: Eq + std::hash::Hash + Clone>(
        slice: &[T],
    ) -> std::collections::HashMap<T, Vec<usize>> {
        let mut hmap = std::collections::HashMap::new();
        for i in 0..slice.len() {
            hmap.entry(slice[i].clone()).or_insert(vec![]).push(i);
        }
        hmap
    }
    pub fn combine<S: Clone, T: Clone, U: std::iter::FromIterator<(S, T)>>(
        left: &[S],
        right: &[T],
    ) -> U {
        let mut ret = vec![];
        for i in 0..left.len() {
            for j in 0..right.len() {
                ret.push((left[i].clone(), right[j].clone()));
            }
        }
        ret.into_iter().collect::<U>()
    }
    pub fn uncount<T: Clone + Eq + std::hash::Hash>(
        hmap: &std::collections::HashMap<T, usize>,
    ) -> Vec<T> {
        hmap.iter()
            .map(|(k, v)| vec![k.clone(); *v])
            .flatten()
            .collect()
    }
    pub fn max_with_index<T: Ord>(slice: &[T]) -> (usize, &T) {
        let mut value: Option<&T> = None;
        let mut index = 0;
        for i in 0..slice.len() {
            if let Some(v) = value {
                if v < &slice[i] {
                    index = i;
                    value = Some(&slice[i]);
                }
            } else {
                index = i;
                value = Some(&slice[i]);
            }
        }
        (index, value.expect("not found max value"))
    }
    pub fn min_with_index<T: Ord>(slice: &[T]) -> (usize, &T) {
        let mut value: Option<&T> = None;
        let mut index = 0;
        for i in 0..slice.len() {
            if let Some(v) = value {
                if v > &slice[i] {
                    index = i;
                    value = Some(&slice[i]);
                }
            } else {
                index = i;
                value = Some(&slice[i]);
            }
        }
        (index, value.expect("not found min value"))
    }
    pub fn split<T: PartialEq + Clone>(slice: &[T], sep: T) -> Vec<Vec<T>> {
        slice.iter().fold(vec![vec![]], |mut acc, x| {
            if x == &sep {
                acc.push(vec![]);
                acc
            } else {
                let last = acc.len() - 1;
                acc[last].push(x.clone());
                acc
            }
        })
    }
    pub fn join<T: std::fmt::Display>(slice: &[T], sep: &str) -> String {
        let strings = slice.iter().map(|t| format!("{}", t)).collect::<Vec<_>>();
        strings.join(sep)
    }
    pub fn coord_comp(slice: &[i64]) -> (Vec<i64>, HashMap<i64, usize>) {
        let mut set = BTreeSet::new();
        for &item in slice {
            set.insert(item);
        }
        let mut hmap = HashMap::new();
        for (i, &v) in set.iter().enumerate() {
            hmap.insert(v, i);
        }
        (set.into_iter().collect::<Vec<_>>(), hmap)
    }
    pub fn shakutori(n: usize, k: i64, a: &[i64]) -> usize {
        let mut sum = 0;
        let mut right = 0;
        let mut ret = 0;
        for left in 0..n {
            while right < n && sum <= k {
                sum += a[right];
                right += 1;
            }
            ret += right - left;
            if right == left {
                right += 1;
            } else {
                sum -= a[left];
            }
        }
        ret
    }
    pub fn inverse(a: &[usize], n: usize) -> Vec<usize> {
        let mut inv = vec![0; n];
        for i in 0..a.len() {
            inv[a[i]] = i;
        }
        inv
    }
    pub fn pow(x: i64, y: i64) -> i64 {
        (x as f64).powi(y as i32) as i64
    }
    pub fn ceil_div<T: Copy + ZeroOne + Add<Output = T> + Sub<Output = T> + Div<Output = T>>(
        x: T,
        y: T,
    ) -> T {
        (x + y - T::one()) / y
    }
    pub fn ceil_mod<
        T: Copy + ZeroOne + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T>,
    >(
        x: T,
        y: T,
    ) -> T {
        ceil_div(x, y) * y
    }
    pub fn unzip<P: Clone, Q: Clone>(v: &[(P, Q)]) -> (Vec<P>, Vec<Q>) {
        (
            v.iter().map(|t| t.0.clone()).collect(),
            v.iter().map(|t| t.1.clone()).collect(),
        )
    }
    pub fn unzip3<P: Clone, Q: Clone, R: Clone>(v: &[(P, Q, R)]) -> (Vec<P>, Vec<Q>, Vec<R>) {
        (
            v.iter().map(|t| t.0.clone()).collect(),
            v.iter().map(|t| t.1.clone()).collect(),
            v.iter().map(|t| t.2.clone()).collect(),
        )
    }
    pub fn base(c: char, b: char) -> usize {
        c as usize - b as usize
    }
    pub fn base_signed(c: char, b: char) -> i64 {
        c as i64 - b as i64
    }
    pub fn is_palindrome<T: Clone + Eq>(chars: &[T]) -> bool {
        let s = chars.to_vec();
        let mut t = s.clone();
        t.reverse();
        (0..s.len()).filter(|&i| s[i] == t[i]).count() == s.len()
    }
}
mod tiny_num_traits {
    pub trait ZeroOne {
        fn zero() -> Self;
        fn one() -> Self;
    }
    macro_rules! impl_zero_one {
        ( $ tpe : ident ) => {
            impl ZeroOne for $tpe {
                fn zero() -> Self {
                    0
                }
                fn one() -> Self {
                    1
                }
            }
        };
    }
    impl_zero_one!(i64);
    impl_zero_one!(i32);
    impl_zero_one!(usize);
}
mod scanner {
    use std::io::{stdin, BufReader, Bytes, Read, Stdin};
    use std::str::FromStr;
    pub struct Scanner {
        buf: Bytes<BufReader<Stdin>>,
    }
    impl Scanner {
        pub fn new() -> Scanner {
            Scanner {
                buf: BufReader::new(stdin()).bytes(),
            }
        }
        pub fn read_next<T: FromStr>(&mut self) -> Option<T> {
            let token = self
                .buf
                .by_ref()
                .map(|c| c.unwrap() as char)
                .skip_while(|c| c.is_whitespace())
                .take_while(|c| !c.is_whitespace())
                .collect::<String>();
            token.parse::<T>().ok()
        }
        pub fn read<T: FromStr>(&mut self) -> T {
            self.read_next().unwrap()
        }
        pub fn readn<T: FromStr>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read::<T>()).collect()
        }
        pub fn chars(&mut self) -> Vec<char> {
            self.read::<String>().chars().collect()
        }
    }
}