アルゴリズムと数学 052

https://atcoder.jp/contests/math-and-algorithm/tasks/abc145_d

(1, 2)方向にx歩、(2, 1)方向にy歩進んで(X, Y)に到達するとすると、

 \displaystyle x = \frac{1}{3}(-X + 2Y)
 \displaystyle y = \frac{1}{3}(2X - Y)

となるので、xとyが0以上の整数になればよいです。しかし、一方が整数になればもう一方も整数になるので、X + Yが3の倍数かを調べればよいです。

// Knight
#![allow(non_snake_case)]


//////////////////// constants ////////////////////

const D: i64 = 1000000007;


//////////////////// library ////////////////////

fn read<T: std::str::FromStr>() -> T {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    line.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
            .map(|e| e.parse().ok().unwrap()).collect()
}

// ax = by + 1 (a, b > 0)
fn linear_diophantine(a: i64, b: i64) -> Option<(i64, i64)> {
    if a == 1 {
        return Some((1, 0))
    }
    
    let q = b / a;
    let r = b % a;
    if r == 0 {
        return None
    }
    let (x1, y1) = linear_diophantine(r, a)?;
    Some((-q * x1 - y1, -x1))
}

fn inverse(a: i64, d: i64) -> i64 {
    let (x, _y) = linear_diophantine(a, d).unwrap();
    if x >= 0 {
        x % d
    }
    else {
        x % d + d
    }
}


//////////////////// process ////////////////////

fn read_input() -> (i64, i64) {
    let v = read_vec();
    (v[0], v[1])
}

fn C(n: i64, m: i64) -> i64 {
    (0..m).fold(1, |x, y| x * (n-y) % D * inverse(y+1, D) % D)
}

fn f(X: i64, Y: i64) -> i64 {
    if (X + Y) % 3 != 0 {
        0
    }
    else {
        let x = (-X + 2*Y) / 3;
        let y = (2*X - Y) / 3;
        if x >= 0 && y >= 0 {
            C(x + y, x)
        }
        else {
            0
        }
    }
}

fn main() {
    let (X, Y) = read_input();
    println!("{}", f(X, Y))
}