Problem:
Score : 600 points

Problem Statement

Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction.

Let us define a function f(r, c) as follows:

f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operation above)

Given are integers r_1, r_2, c_1, and c_2.
Find the sum of f(i, j) over all pair of integers (i, j) such that r_1 ≤ i ≤ r_2 and c_1 ≤ j ≤ c_2, and compute this value modulo (10^9+7).

Constraints

1 ≤ r_1 ≤ r_2 ≤ 10^6

1 ≤ c_1 ≤ c_2 ≤ 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r_1 c_1 r_2 c_2

Output

Print the sum of f(i, j) modulo (10^9+7).

Sample Input 1

1 1 2 2

Sample Output 1

14

For example, there are two paths from the point (0, 0) to the point (1, 1): (0,0) → (0,1) → (1,1) and (0,0) → (1,0) → (1,1), so f(1,1)=2.

Similarly, f(1,2)=3, f(2,1)=3, and f(2,2)=6. Thus, the sum is 14.

Sample Input 2

314 159 2653 589

Sample Output 2

602215194

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

#![allow(unused_macros, deprecated)]

#[allow(dead_code)]
mod utils {
    use std::io::{
        self, BufRead, BufReader, BufWriter, Seek, SeekFrom, Stdin, StdinLock, Stdout, StdoutLock,
        Write,
    };
    use std::mem;
    use std::ops::{Deref, DerefMut};
    use std::ptr;
    use std::slice;
    use std::str::{self, FromStr};

    #[inline]
    fn is_space_or_line_break(b: &u8) -> bool {
        *b == b' ' || *b == b'\n'
    }

    pub struct Scanner<R: BufRead> {
        reader: R,
        buf: Vec<u8>,
    }

    impl<R: BufRead> Scanner<R> {
        #[inline]
        pub fn new(reader: R) -> Scanner<R> {
            Scanner {
                reader: reader,
                buf: Vec::with_capacity(100),
            }
        }

        pub fn read<T: FromStr>(&mut self) -> T {
            self.read_until(is_space_or_line_break);
            self.parse()
        }

        pub fn read2<T1: FromStr, T2: FromStr>(&mut self) -> (T1, T2) {
            (self.read(), self.read())
        }

        pub fn read3<T1: FromStr, T2: FromStr, T3: FromStr>(&mut self) -> (T1, T2, T3) {
            (self.read(), self.read(), self.read())
        }

        pub fn read4<T1: FromStr, T2: FromStr, T3: FromStr, T4: FromStr>(
            &mut self,
        ) -> (T1, T2, T3, T4) {
            (self.read(), self.read(), self.read(), self.read())
        }

        pub fn reads(&mut self) -> &str {
            self.read_until(is_space_or_line_break);
            unsafe { str::from_utf8_unchecked(&self.buf) }
        }

        pub fn readl(&mut self) -> &str {
            self.buf.clear();
            self.reader.read_until(b'\n', &mut self.buf).unwrap();
            let bytes = if self.buf.last() == Some(&b'\n') {
                &self.buf[..self.buf.len() - 1]
            } else {
                &self.buf
            };
            unsafe { str::from_utf8_unchecked(&bytes) }
        }

        pub fn read_vec<T: FromStr>(&mut self, count: usize) -> Vec<T> {
            (0..count).map(|_| self.read()).collect()
        }

        fn read_until<P: FnMut(&u8) -> bool>(&mut self, mut predicate: P) {
            self.buf.clear();
            let mut first = true;

            // https://doc.rust-lang.org/src/std/io/mod.rs.html#1623-1649
            loop {
                let (done, used) = {
                    let available = self.reader.fill_buf().unwrap();
                    if first && available.len() == 0 {
                        panic!("Scan Error (EOF reached)");
                    }

                    match available.iter().position(&mut predicate) {
                        Some(0) if first => (false, 1),
                        Some(i) => {
                            self.buf.extend_from_slice(&available[..i]);
                            (true, i + 1)
                        }
                        None => {
                            self.buf.extend_from_slice(available);
                            (false, available.len())
                        }
                    }
                };

                self.reader.consume(used);
                if done || used == 0 {
                    return;
                }

                first = false;
            }
        }

        #[inline]
        fn parse<T: FromStr>(&mut self) -> T {
            // 文字列をT型へパースする
            let elem = unsafe { str::from_utf8_unchecked(&self.buf) };
            elem.parse()
                .unwrap_or_else(|_| panic!(format!("failed parsing: {}", elem)))
        }
    }

    impl<R: BufRead + Seek> Seek for Scanner<R> {
        #[inline]
        fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
            self.reader.seek(pos)
        }
    }

    pub struct StdinScanner {
        stdin: Stdin,
        scanner: Scanner<BufReader<StdinLock<'static>>>,
    }

    impl StdinScanner {
        #[inline]
        pub fn new() -> StdinScanner {
            let stdin = io::stdin();
            let stdinlock = unsafe { mem::transmute(stdin.lock()) };
            let reader = BufReader::with_capacity(4096, stdinlock);
            let scanner = Scanner::new(reader);
            StdinScanner {
                stdin: stdin,
                scanner: scanner,
            }
        }
    }

    impl Deref for StdinScanner {
        type Target = Scanner<BufReader<StdinLock<'static>>>;

        #[inline]
        fn deref(&self) -> &Self::Target {
            &self.scanner
        }
    }

    impl DerefMut for StdinScanner {
        #[inline]
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.scanner
        }
    }

    pub struct StdoutWriter {
        stdout: Stdout,
        writer: BufWriter<StdoutLock<'static>>,
    }

    impl StdoutWriter {
        #[inline]
        pub fn new() -> StdoutWriter {
            let stdout = io::stdout();
            let stdoutlock = unsafe { mem::transmute(stdout.lock()) };
            let writer = BufWriter::with_capacity(4096, stdoutlock);
            StdoutWriter {
                stdout: stdout,
                writer: writer,
            }
        }

        pub fn write<T: Writable>(&mut self, v: T) {
            v.display(&mut self.writer);
        }

        pub fn writeln<T: Writable>(&mut self, v: T) {
            v.display(&mut self.writer);
            self.writer.write_all(b"\n").unwrap();
        }

        pub fn write_horizontal<I>(&mut self, iter: I)
        where
            I: IntoIterator,
            I::Item: Writable,
        {
            let mut it = iter.into_iter();
            if let Some(elem) = it.next() {
                elem.display(&mut self.writer);
            } else {
                return;
            }

            for elem in it {
                elem.display(&mut self.writer);
                self.writer.write_all(b" ").unwrap();
            }
        }

        pub fn write_vertical<I>(&mut self, iter: I)
        where
            I: IntoIterator,
            I::Item: Writable,
        {
            let mut it = iter.into_iter();
            if let Some(elem) = it.next() {
                elem.display(&mut self.writer);
            } else {
                return;
            }

            for elem in it {
                elem.display(&mut self.writer);
                self.writer.write_all(b"\n").unwrap();
            }
        }
    }

    impl Write for StdoutWriter {
        #[inline]
        fn flush(&mut self) -> io::Result<()> {
            self.writer.flush()
        }

        #[inline]
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.writer.write(buf)
        }
    }

    static DEC_DIGITS_LUT: &'static [u8; 200] = b"0001020304050607080910111213141516171819\
            2021222324252627282930313233343536373839\
            4041424344454647484950515253545556575859\
            6061626364656667686970717273747576777879\
            8081828384858687888990919293949596979899";

    fn write_int<W: Write>(mut writer: W, mut n: u64, is_negative: bool) {
        unsafe {
            let mut buf: [u8; 39] = mem::uninitialized();
            let buf_ptr_start = buf.as_mut_ptr().offset(39);
            let mut buf_ptr = buf_ptr_start;
            let lut_ptr = DEC_DIGITS_LUT.as_ptr();

            while n >= 10000 {
                let rem = (n % 10000) as isize;
                n /= 10000;

                let d1 = (rem / 100) << 1;
                let d2 = (rem % 100) << 1;
                buf_ptr = buf_ptr.offset(-4);
                ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr, 2);
                ptr::copy_nonoverlapping(lut_ptr.offset(d2), buf_ptr.offset(2), 2);
            }

            let mut n = n as isize; // possibly reduce 64bit math

            // decode 2 more chars, if > 2 chars
            if n >= 100 {
                let d1 = (n % 100) << 1;
                n /= 100;
                buf_ptr = buf_ptr.offset(-2);
                ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr, 2);
            }

            // decode last 1 or 2 chars
            if n < 10 {
                buf_ptr = buf_ptr.offset(-1);
                *buf_ptr = (n as u8) + b'0';
            } else {
                let d1 = n << 1;
                buf_ptr = buf_ptr.offset(-2);
                ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr, 2);
            }

            if is_negative {
                buf_ptr = buf_ptr.offset(-1);
                *buf_ptr = b'-';
            }

            let buf_slice =
                slice::from_raw_parts(buf_ptr, buf_ptr_start as usize - buf_ptr as usize);

            writer.write_all(buf_slice).unwrap();
        }
    }

    pub trait Writable {
        fn display<W: Write>(&self, writer: &mut W);
    }

    impl Writable for str {
        #[inline]
        fn display<W: Write>(&self, writer: &mut W) {
            writer.write_all(self.as_bytes()).unwrap()
        }
    }

    impl<'a> Writable for &'a str {
        #[inline]
        fn display<W: Write>(&self, writer: &mut W) {
            writer.write_all(self.as_bytes()).unwrap()
        }
    }

    impl Writable for String {
        #[inline]
        fn display<W: Write>(&self, writer: &mut W) {
            writer.write_all(self.as_bytes()).unwrap()
        }
    }

    impl Writable for bool {
        #[inline]
        fn display<W: Write>(&self, writer: &mut W) {
            let s: &'static [u8] = if *self { b"Yes" } else { b"No" };
            writer.write_all(s).unwrap();
        }
    }

    macro_rules! impl_writable_int {
        ($($int:ty)*) => {
            $(
                impl Writable for $int {
                    #[allow(unused_comparisons)]
                    fn display<W: Write>(&self, writer: &mut W) {
                        let is_negative = !(*self >= 0);
                        let abs = if is_negative {
                            (!*self as u64).wrapping_add(1)
                        } else {
                            *self as u64
                        };
                        write_int(writer, abs, is_negative);
                    }
                }
            )*
        };
    }

    macro_rules! impl_writable_float {
        ($($float:ty)*) => {
            $(
                impl Writable for $float {
                    #[inline]
                    fn display<W: Write>(&self, writer: &mut W) {
                        write!(writer, "{}", *self).unwrap();
                    }
                }
            )*
        }
    }

    impl_writable_int!(u8 u16 u32 u64 usize i8 i16 i32 i64 isize);
    impl_writable_float!(f32 f64);

    pub static mut SCANNER: *mut StdinScanner = 0 as *mut StdinScanner;
    pub static mut WRITER: *mut StdoutWriter = 0 as *mut StdoutWriter;

    #[inline]
    pub fn atcoder_initialize() {
        unsafe {
            SCANNER = mem::transmute(Box::new(StdinScanner::new()));
            WRITER = mem::transmute(Box::new(StdoutWriter::new()));
        }
    }

    #[inline]
    pub fn atcoder_finish() {
        unsafe {
            (*WRITER).flush().unwrap();
        }
    }
}

macro_rules! input {
    () => {};
    (@scanner $scanner:ident, @pred [ $($pred:tt)* ], $var:tt : $t:tt) => {
        let $($pred)* $var = scan!($scanner, $t);
    };
    (@scanner $scanner:ident,) => {};
    (@scanner $scanner:ident, $var:tt : $t:tt) => {
        input!(@scanner $scanner, @pred [], $var : $t);
    };
    (@scanner $scanner:ident, mut $var:tt : $t:tt) => {
        input!(@scanner $scanner, @pred [mut], $var : $t);
    };
    (@scanner $scanner:ident, $var:tt : $t:tt, $($r:tt)*) => {
        input!(@scanner $scanner, $var : $t);
        input!(@scanner $scanner, $($r)*);
    };
    (@scanner $scanner:ident, mut $var:tt : $t:tt, $($r:tt)*) => {
        input!(@scanner $scanner, mut $var : $t);
        input!(@scanner $scanner, $($r)*);
    };
    ($($r:tt)*) => {
        let scanner_ref = unsafe { &mut *$crate::utils::SCANNER };
        input!(@scanner scanner_ref, $($r)*);
    }
}

macro_rules! scan {
    ($scanner:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| scan!($scanner; $t)).collect::<Vec<_>>()
    };
    ($scanner:ident, usize1) => {
        scan!($scanner; usize) - 1
    };
    ($scanner:ident, line) => {
        $scanner.readl().to_string()
    };
    ($scanner:ident, $t:ty) => {
        $scanner.read::<$t>()
    };
}

macro_rules! pprint {
    ($value:expr) => {
        unsafe {
            (*$crate::utils::WRITER).write($value);
        }
    };
    ($value:expr, $($r:tt)*) => {
        let writer = unsafe { &*$crate::utils::WRITER };
        writer.write($value);
        writer.write(" ");
        pprint!($($r)*);
    };
}

macro_rules! pprintln {
    ($value:expr) => {
        unsafe {
            (*$crate::utils::WRITER).writeln($value);
        }
    };
    ($value:expr, $($r:tt)*) => {
        let writer = unsafe { &*$crate::utils::WRITER };
        writer.write($value);
        writer.write(" ");
        pprintln!($($r)*);
    };
}

macro_rules! atcoder_main {
    ($func:ident) => {
        fn main() {
            $crate::utils::atcoder_initialize();
            $func();
            $crate::utils::atcoder_finish();
        }
    };
}

use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign};

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ModU64 {
    num: u64,
    prime: u64,
}

impl ModU64 {
    pub fn new(num: u64, prime: u64) -> ModU64 {
        ModU64 {
            num: num % prime,
            prime: prime
        }
    }

    pub fn pow(&self, mut n: u64) -> ModU64 {
        let mut a = self.num;
        let mut res = 1;
        while n > 0 {
            if n & 1 == 1 {
                res = res * a % self.prime;
            }
            a = a * a % self.prime;
            n >>= 1;
        }

        return ModU64::new(res, self.prime);
    }

    pub fn recip(&self) -> ModU64 {
        return self.pow(self.prime - 2);
    }

    pub fn to_u64(&self) -> u64 {
        self.num
    }
}

impl AddAssign<u64> for ModU64 {
    fn add_assign(&mut self, rhs: u64) {
        self.num = (self.num + rhs) % self.prime;
    }
}

impl SubAssign<u64> for ModU64 {
    fn sub_assign(&mut self, rhs: u64) {
        let tmp = rhs % self.prime;
        if self.num >= tmp {
            self.num -= tmp;
        } else {
            self.num += self.prime - tmp;
        }
    }
}

impl MulAssign<u64> for ModU64 {
    fn mul_assign(&mut self, rhs: u64) {
        // TODO: avoid overflow
        self.num *= rhs;
        self.num %= self.prime;
    }
}

impl DivAssign<u64> for ModU64 {
    fn div_assign(&mut self, rhs: u64) {
        *self *= ModU64::new(rhs, self.prime).recip().num;
    }
}

impl Add<u64> for ModU64 {
    type Output = ModU64;
    fn add(self, rhs: u64) -> ModU64 {
        let mut cp = self.clone();
        cp += rhs;
        return cp;
    }
}

impl Sub<u64> for ModU64 {
    type Output = ModU64;
    fn sub(self, rhs: u64) -> ModU64 {
        let mut cp = self.clone();
        cp -= rhs;
        return cp;
    }
}

impl Mul<u64> for ModU64 {
    type Output = ModU64;
    fn mul(self, rhs: u64) -> ModU64 {
        let mut cp = self.clone();
        cp *= rhs;
        return cp;
    }
}

impl Div<u64> for ModU64 {
    type Output = ModU64;
    fn div(self, rhs: u64) -> ModU64 {
        let mut cp = self.clone();
        cp /= rhs;
        return cp;
    }
}

#[derive(Debug)]
struct ModCombination {
    prime: u64,
    fact: Vec<u64>,
    ifact: Vec<u64>,
}

impl ModCombination {
    pub fn with_capacity(capacity: usize, prime: u64) -> ModCombination {
        let mut fact = Vec::with_capacity(capacity);
        let mut ifact = Vec::with_capacity(capacity);
        fact.push(1);
        ifact.push(1);

        ModCombination {
            prime: prime,
            fact: fact,
            ifact: ifact,
        }
    }

    pub fn run(&mut self, n: u64, r: u64) -> u64 {
        assert!(n < self.prime);

        if n < r {
            return 0;
        }

        if r == 0 || n == r {
            return 1;
        }

        self.update_factorial(n);

        unsafe {
            let n_fac = self.fact.get_unchecked(n as usize);
            let r_fac = self.ifact.get_unchecked(r as usize);
            let npr_fac = self.ifact.get_unchecked((n - r) as usize);

            n_fac * (r_fac * npr_fac % self.prime) % self.prime
        }
    }

    fn update_factorial(&mut self, n: u64) {
        let current_size = self.fact.len() as u64;
        if current_size > n {
            return;
        }

        self.fact.reserve((n + 1) as usize);
        self.ifact.reserve((n + 1) as usize);

        unsafe {
            self.ifact.set_len((n + 1) as usize);
        }

        let mut last_fact = self.fact.last().unwrap().clone();
        for i in current_size..n + 1 {
            last_fact = last_fact * i % self.prime;
            self.fact.push(last_fact);
        }

        let mut last_ifact = ModU64::new(last_fact, self.prime).recip().num;
        self.ifact[n as usize] = last_ifact;
        for i in (current_size..n).rev() {
            last_ifact = last_ifact * (i + 1) % self.prime;
            unsafe {
                *self.ifact.get_unchecked_mut(i as usize) = last_ifact;
            }
        }
    }
}

fn run() {
    input! {
        r1: u64,
        c1: u64,
        r2: u64,
        c2: u64,
    }

    let mut combinator = ModCombination::with_capacity(2000005, 1000000007);
    let mut g = |r: u64, c: u64| -> u64 {
        combinator.run(r + c + 2, c + 1)
    };

    let mut result = ModU64::new(0, 1000000007);
    result += g(r2, c2);
    result += g(r1 - 1, c1 - 1);
    result -= g(r1 - 1, c2);
    result -= g(r2, c1 - 1);

    pprintln!(result.to_u64());
}

atcoder_main!(run);