アルゴリズムと数学 075

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

これも数え方の問題ですね。例の20や22が頂点でいくつカウントされるか考えます。頂点までのパスの数なので、パスカルの三角形と同じになります。

// Pyramid
#![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() -> Vec<i64> {
    let _N: usize = read();
    let A = read_vec();
    A
}

fn f(A: Vec<i64>) -> i64 {
    let N = A.len();
    let mut s: i64 = A[0];
    let mut c: i64 = 1;
    for i in 1..N {
        c = c * ((N - i) as i64) % D * inverse(i as i64, D) % D;
        s = (s + c * A[i]) % D
    }
    s
}

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