結果

問題 No.194 フィボナッチ数列の理解(1)
ユーザー urectanc
提出日時 2025-09-03 23:02:59
言語 Rust
(1.83.0 + proconio)
結果
WA  
実行時間 -
コード長 9,190 bytes
コンパイル時間 13,604 ms
コンパイル使用メモリ 398,160 KB
実行使用メモリ 11,336 KB
最終ジャッジ日時 2025-09-03 23:03:15
合計ジャッジ時間 14,280 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29 WA * 8
権限があれば一括ダウンロードができます

ソースコード

diff #

use modint::ModInt1000000007;
use proconio::{input, marker::Usize1};

type Mint = ModInt1000000007;
type Mat = Vec<Vec<Mint>>;

fn main() {
    input! {
        n: usize, k: Usize1,
        a: [Mint; n],
    }

    let (f, s) = if n > 30 { solve1(k, a) } else { solve2(k, a) };
    println!("{f} {s}");
}

fn solve1(k: usize, mut a: Vec<Mint>) -> (Mint, Mint) {
    let n = a.len();
    let mut f = a.iter().sum::<Mint>();
    let mut s = f * 2;

    for i in n..k {
        f = f * 2 - a[i - n];
        s += f;
        a.push(f);
    }

    (f, s)
}

fn solve2(k: usize, a: Vec<Mint>) -> (Mint, Mint) {
    let n = a.len();

    let mut s = vec![Mint::new(0); n + 1];
    for (i, a) in a.iter().enumerate() {
        s[i + 1] = s[i] + a;
    }

    let mut mat_f = vec![vec![Mint::new(0); n]; n];
    for i in 0..n {
        mat_f[0][i] = 1.into();
        if i > 0 {
            mat_f[i][i - 1] = 1.into();
        }
    }
    let mut mat_s = vec![vec![Mint::new(0); n + 1]; n + 1];
    mat_s[0][0] = 2.into();
    mat_s[0][n] = (-1).into();
    for i in 1..=n {
        mat_s[i][i - 1] = 1.into();
    }

    let pow_f = pow(&mat_f, k + 1 - n);
    let pow_s = pow(&mat_s, k + 1 - n);
    let f = pow_f[0].iter().rev().zip(&a).map(|(&x, &y)| x * y).sum();
    let s = pow_s[0].iter().rev().zip(&s).map(|(&x, &y)| x * y).sum();
    (f, s)
}

fn mul(a: &Mat, b: &Mat) -> Mat {
    let n = a.len();
    let mut res = vec![vec![Mint::new(0); n]; n];
    for i in 0..n {
        for j in 0..n {
            for k in 0..n {
                res[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    res
}

fn pow(a: &Mat, mut k: usize) -> Mat {
    assert!(k > 0);
    k -= 1;
    let mut res = a.clone();
    let mut pow = a.clone();
    while k > 0 {
        if k & 1 == 1 {
            res = mul(&res, &pow);
        }
        pow = mul(&pow, &pow);
        k >>= 1;
    }
    res
}

#[allow(dead_code)]
mod modint {
    use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

    pub type ModInt998244353 = ModInt<998244353>;
    pub type ModInt1000000007 = ModInt<1000000007>;

    type ModIntInner = u64;

    #[derive(Clone, Copy, PartialEq, Eq)]
    pub struct ModInt<const M: ModIntInner> {
        val: ModIntInner,
    }

    impl<const M: ModIntInner> ModInt<M> {
        const IS_PRIME: bool = is_prime(M as u32);

        pub const fn modulus() -> ModIntInner {
            M
        }

        pub const fn new(val: ModIntInner) -> Self {
            assert!(M < (1 << 31));
            Self {
                val: val.rem_euclid(M),
            }
        }

        pub const fn new_unchecked(val: ModIntInner) -> Self {
            Self { val }
        }

        pub const fn val(&self) -> ModIntInner {
            self.val
        }

        pub fn pow(self, mut exp: u64) -> Self {
            let mut result = Self::new(1);
            let mut base = self;
            while exp > 0 {
                if exp & 1 == 1 {
                    result *= base;
                }
                base *= base;
                exp >>= 1;
            }
            result
        }

        pub fn inv(self) -> Self {
            assert!(Self::IS_PRIME);
            self.pow(M as u64 - 2).into()
        }
    }

    impl<const M: ModIntInner> std::fmt::Display for ModInt<M> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.val)
        }
    }

    impl<const M: ModIntInner> std::fmt::Debug for ModInt<M> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.val)
        }
    }

    impl<const M: ModIntInner> std::str::FromStr for ModInt<M> {
        type Err = std::num::ParseIntError;
        fn from_str(s: &str) -> Result<Self, Self::Err> {
            let value = s.parse::<ModIntInner>()?;
            Ok(ModInt::new(value))
        }
    }

    impl<const M: ModIntInner> Neg for ModInt<M> {
        type Output = Self;
        fn neg(mut self) -> Self::Output {
            if self.val > 0 {
                self.val = M - self.val;
            }
            self
        }
    }

    impl<const M: ModIntInner, T: Into<ModInt<M>>> AddAssign<T> for ModInt<M> {
        fn add_assign(&mut self, rhs: T) {
            self.val += rhs.into().val;
            if self.val >= M {
                self.val -= M;
            }
        }
    }

    impl<const M: ModIntInner, T: Into<ModInt<M>>> SubAssign<T> for ModInt<M> {
        fn sub_assign(&mut self, rhs: T) {
            self.val = self.val.wrapping_sub(rhs.into().val);
            if self.val > M {
                self.val = self.val.wrapping_add(M);
            }
        }
    }

    impl<const M: ModIntInner, T: Into<ModInt<M>>> MulAssign<T> for ModInt<M> {
        fn mul_assign(&mut self, rhs: T) {
            self.val = self.val * rhs.into().val % M;
        }
    }

    impl<const M: ModIntInner, T: Into<ModInt<M>>> DivAssign<T> for ModInt<M> {
        fn div_assign(&mut self, rhs: T) {
            *self *= rhs.into().inv();
        }
    }

    macro_rules! impl_binnary_operators {
    ($({ $op: ident, $op_assign: ident, $fn: ident, $fn_assign: ident}),*) => {$(
        impl<const M: ModIntInner, T: Into<ModInt<M>>> $op<T> for ModInt<M> {
            type Output = ModInt<M>;
            fn $fn(mut self, rhs: T) -> ModInt<M> {
                self.$fn_assign(rhs.into());
                self
            }
        }

        impl<const M: ModIntInner> $op<&ModInt<M>> for ModInt<M> {
            type Output = ModInt<M>;
            fn $fn(self, rhs: &ModInt<M>) -> ModInt<M> {
                self.$fn(*rhs)
            }
        }

        impl<const M: ModIntInner, T: Into<ModInt<M>>> $op<T> for &ModInt<M> {
            type Output = ModInt<M>;
            fn $fn(self, rhs: T) -> ModInt<M> {
                (*self).$fn(rhs.into())
            }
        }

        impl<const M: ModIntInner> $op<&ModInt<M>> for &ModInt<M> {
            type Output = ModInt<M>;
            fn $fn(self, rhs: &ModInt<M>) -> ModInt<M> {
                (*self).$fn(*rhs)
            }
        }

        impl<const M: ModIntInner> $op_assign<&ModInt<M>> for ModInt<M> {
            fn $fn_assign(&mut self, rhs: &ModInt<M>) {
                *self = self.$fn(*rhs);
            }
        }
    )*};
}

    impl_binnary_operators!(
        {Add, AddAssign, add, add_assign},
        {Sub, SubAssign, sub, sub_assign},
        {Mul, MulAssign, mul, mul_assign},
        {Div, DivAssign, div, div_assign}
    );

    impl<const M: ModIntInner> std::iter::Sum for ModInt<M> {
        fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
            iter.fold(Self::new(0), Add::add)
        }
    }

    impl<'a, const M: ModIntInner> std::iter::Sum<&'a Self> for ModInt<M> {
        fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
            iter.fold(Self::new(0), Add::add)
        }
    }

    impl<const M: ModIntInner> std::iter::Product for ModInt<M> {
        fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
            iter.fold(Self::new(1), Mul::mul)
        }
    }

    impl<'a, const M: ModIntInner> std::iter::Product<&'a Self> for ModInt<M> {
        fn product<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
            iter.fold(Self::new(1), Mul::mul)
        }
    }

    macro_rules! impl_rem_euclid_signed {
    ($($ty:tt),*) => {
        $(
            impl<const M: ModIntInner> From<$ty> for ModInt<M> {
                fn from(value: $ty) -> ModInt<M> {
                    Self::new_unchecked((value as i64).rem_euclid(M as i64) as ModIntInner)
                }
            }
        )*
    };
}
    impl_rem_euclid_signed!(i8, i16, i32, i64, isize);

    macro_rules! impl_rem_euclid_unsigned {
    ($($ty:tt),*) => {
        $(
            impl<const M: ModIntInner> From<$ty> for ModInt<M> {
                fn from(value: $ty) -> ModInt<M> {
                    Self::new_unchecked((value as u64).rem_euclid(M as u64) as ModIntInner)
                }
            }
        )*
    };
}
    impl_rem_euclid_unsigned!(u8, u16, u32, u64, usize);

    const fn is_prime(n: u32) -> bool {
        const fn miller_rabin(n: u32, witness: u32) -> bool {
            let (n, witness) = (n as u64, witness as u64);
            let mut d = n >> (n - 1).trailing_zeros();
            let mut y = {
                let (mut res, mut pow, mut e) = (1, witness, d);
                while e > 0 {
                    if e & 1 == 1 {
                        res = res * pow % n;
                    }
                    pow = pow * pow % n;
                    e >>= 1;
                }
                res
            };
            while d != n - 1 && y != 1 && y != n - 1 {
                y = y * y % n;
                d <<= 1;
            }
            y == n - 1 || d & 1 == 1
        }

        const WITNESS: [u32; 3] = [2, 7, 61];

        if n == 1 || n % 2 == 0 {
            return n == 2;
        }

        let mut i = 0;
        while i < WITNESS.len() {
            if !miller_rabin(n, WITNESS[i]) {
                return false;
            }
            i += 1;
        }

        true
    }
}
0