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: Wrong Answer)

#![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();
        }
    };
}

#[derive(Clone)]
struct ModCombinationCache {
    fac: u64,
    finv: u64,
    inv: u64,
}

struct ModCombinator {
    prime: u64,
    factorial: Vec<ModCombinationCache>,
}

impl ModCombinator {
    pub fn with_capacity(capacity: usize, prime: u64) -> ModCombinator {
        let mut factorial = Vec::with_capacity(capacity);
        factorial.push(ModCombinationCache {
            fac: 1,
            finv: 1,
            inv: 0,
        });
        factorial.push(ModCombinationCache {
            fac: 1,
            finv: 1,
            inv: 1,
        });

        ModCombinator {
            prime: prime,
            factorial: factorial,
        }
    }

    pub fn run(&mut self, n: u64, r: u64) -> u64 {
        if n < r {
            return 0;
        }

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

        // update cache
        self.factorial.reserve(n as usize);

        // update factorial
        let mut last_fac: ModCombinationCache = self.factorial.last().unwrap().clone();

        for i in self.factorial.len() as u64..n + 1 {
            let inv = self.prime
                - self.factorial[(self.prime % i) as usize].inv * (self.prime / i) % self.prime;
            let new_fac = ModCombinationCache {
                fac: last_fac.fac * i % self.prime,
                inv: inv,
                finv: last_fac.finv * inv % self.prime,
            };
            self.factorial.push(new_fac.clone());
            last_fac = new_fac;
        }

        unsafe {
            let n_fac = self.factorial.get_unchecked(n as usize).fac;
            let r_fac = self.factorial.get_unchecked(r as usize).finv;
            let npr_fac = self.factorial.get_unchecked((n - r) as usize).finv;

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

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

    let mut combinator = ModCombinator::with_capacity(2000005, 1000000007);

    let mut result = 0u64;
    result += combinator.run(r2 + c2 + 2, r2 + 1);
    result += combinator.run(r1 + c1, r1);
    result -= combinator.run(c1 + r2 + 1, c1);
    result -= combinator.run(c2 + r1 + 1, r1);

    pprintln!(result);
}

atcoder_main!(run);