結果

問題 No.554 recurrence formula
ユーザー taotao54321taotao54321
提出日時 2018-10-11 09:09:58
言語 Rust
(1.77.0)
結果
AC  
実行時間 32 ms / 2,000 ms
コード長 1,426 bytes
コンパイル時間 496 ms
コンパイル使用メモリ 152,832 KB
実行使用メモリ 5,888 KB
最終ジャッジ日時 2024-04-20 19:40:30
合計ジャッジ時間 1,239 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 1 ms
5,376 KB
testcase_02 AC 1 ms
5,376 KB
testcase_03 AC 1 ms
5,376 KB
testcase_04 AC 1 ms
5,376 KB
testcase_05 AC 1 ms
5,376 KB
testcase_06 AC 1 ms
5,376 KB
testcase_07 AC 1 ms
5,376 KB
testcase_08 AC 1 ms
5,376 KB
testcase_09 AC 1 ms
5,376 KB
testcase_10 AC 1 ms
5,376 KB
testcase_11 AC 2 ms
5,376 KB
testcase_12 AC 2 ms
5,376 KB
testcase_13 AC 3 ms
5,376 KB
testcase_14 AC 3 ms
5,376 KB
testcase_15 AC 4 ms
5,376 KB
testcase_16 AC 4 ms
5,376 KB
testcase_17 AC 3 ms
5,376 KB
testcase_18 AC 3 ms
5,376 KB
testcase_19 AC 31 ms
5,760 KB
testcase_20 AC 32 ms
5,888 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#![allow(non_snake_case)]

use std::io::{ self, prelude::* };

macro_rules! pick {
    ($tokens:expr) => {
        $tokens.next().unwrap().parse().expect("parse error")
    }
}

fn powmod(a: i64, b: i64, p: i64) -> i64 {
    if b == 0 { return 1; }
    if b == 1 { return a%p; }

    let (q, r) = (b/2, b%2);
    let mut res = 1;
    res *= powmod(a, q, p).pow(2);
    res %= p;
    if r == 1 {
        res *= a;
        res %= p;
    }
    res
}

fn invmod(a: i64, p: i64) -> i64 {
    powmod(a, p-2, p)
}

struct Solver {
    memo: Vec<Option<i64>>,
}

impl Solver {
    const MOD: i64 = 1_000_000_007;

    fn new() -> Self {
        let mut memo = vec![None; 100001];
        memo[1] = Some(1);
        memo[2] = Some(2);
        memo[3] = Some(6);

        Self {
            memo,
        }
    }

    fn f(&mut self, n: i64) -> i64 {
        if let Some(res) = self.memo[n as usize] { return res; }

        let mut res = 0;
        res += n * self.f(n-2);
        res %= Solver::MOD;
        res *= invmod(n-2, Solver::MOD);
        res += n*self.f(n-1);
        res %= Solver::MOD;
        self.memo[n as usize] = Some(res);
        res
    }
}

fn main() {
    let mut s = String::new();
    io::stdin().read_to_string(&mut s).expect("i/o error");
    let mut tokens = s.split_whitespace();

    let N: i64 = pick!(tokens);

    let mut solver = Solver::new();
    let ans = solver.f(N);

    println!("{}", ans);
}
0