結果

問題 No.1411 Hundreds of Conditions Sequences
ユーザー ngtkanangtkana
提出日時 2020-12-02 00:25:16
言語 Rust
(1.77.0 + proconio)
結果
AC  
実行時間 545 ms / 2,000 ms
コード長 19,841 bytes
コンパイル時間 19,197 ms
コンパイル使用メモリ 386,560 KB
実行使用メモリ 40,988 KB
最終ジャッジ日時 2024-09-22 10:57:41
合計ジャッジ時間 31,023 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,812 KB
testcase_01 AC 2 ms
6,812 KB
testcase_02 AC 1 ms
6,812 KB
testcase_03 AC 1 ms
6,944 KB
testcase_04 AC 1 ms
6,940 KB
testcase_05 AC 1 ms
6,944 KB
testcase_06 AC 1 ms
6,940 KB
testcase_07 AC 1 ms
6,940 KB
testcase_08 AC 1 ms
6,944 KB
testcase_09 AC 1 ms
6,944 KB
testcase_10 AC 1 ms
6,944 KB
testcase_11 AC 1 ms
6,940 KB
testcase_12 AC 275 ms
37,660 KB
testcase_13 AC 214 ms
34,384 KB
testcase_14 AC 124 ms
30,092 KB
testcase_15 AC 207 ms
34,220 KB
testcase_16 AC 44 ms
25,940 KB
testcase_17 AC 203 ms
33,764 KB
testcase_18 AC 277 ms
37,420 KB
testcase_19 AC 301 ms
38,496 KB
testcase_20 AC 126 ms
30,064 KB
testcase_21 AC 314 ms
39,356 KB
testcase_22 AC 135 ms
30,596 KB
testcase_23 AC 280 ms
37,596 KB
testcase_24 AC 31 ms
25,000 KB
testcase_25 AC 281 ms
37,444 KB
testcase_26 AC 204 ms
34,072 KB
testcase_27 AC 128 ms
30,196 KB
testcase_28 AC 237 ms
35,488 KB
testcase_29 AC 56 ms
26,584 KB
testcase_30 AC 179 ms
32,772 KB
testcase_31 AC 166 ms
32,196 KB
testcase_32 AC 319 ms
39,552 KB
testcase_33 AC 317 ms
39,632 KB
testcase_34 AC 316 ms
39,460 KB
testcase_35 AC 318 ms
39,404 KB
testcase_36 AC 318 ms
39,524 KB
testcase_37 AC 318 ms
39,548 KB
testcase_38 AC 319 ms
39,416 KB
testcase_39 AC 315 ms
39,484 KB
testcase_40 AC 321 ms
39,524 KB
testcase_41 AC 322 ms
39,496 KB
testcase_42 AC 323 ms
39,504 KB
testcase_43 AC 319 ms
39,492 KB
testcase_44 AC 320 ms
39,540 KB
testcase_45 AC 317 ms
39,624 KB
testcase_46 AC 319 ms
39,564 KB
testcase_47 AC 316 ms
39,476 KB
testcase_48 AC 324 ms
39,536 KB
testcase_49 AC 321 ms
39,508 KB
testcase_50 AC 318 ms
39,472 KB
testcase_51 AC 317 ms
39,344 KB
testcase_52 AC 351 ms
39,640 KB
testcase_53 AC 349 ms
39,616 KB
testcase_54 AC 344 ms
39,660 KB
testcase_55 AC 347 ms
39,584 KB
testcase_56 AC 349 ms
39,604 KB
testcase_57 AC 351 ms
39,624 KB
testcase_58 AC 349 ms
39,668 KB
testcase_59 AC 346 ms
39,648 KB
testcase_60 AC 350 ms
39,660 KB
testcase_61 AC 354 ms
39,544 KB
testcase_62 AC 545 ms
38,592 KB
testcase_63 AC 400 ms
40,988 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
warning: unused imports: `Leaf`, `Tuple`, `VecLen`
   --> src/main.rs:376:37
    |
376 |         pub use self::multi_token::{Leaf, Parser, ParserTuple, RawTuple, Tuple, VecLen};
    |                                     ^^^^                                 ^^^^^  ^^^^^^
    |
    = note: `#[warn(unused_imports)]` on by default

warning: unused import: `with_str`
   --> src/main.rs:631:35
    |
631 |     pub use self::i::{with_stdin, with_str};
    |                                   ^^^^^^^^

warning: unused imports: `ParserTuple`, `Parser`, `RawTuple`, `Token`, `Usize1`
   --> src/main.rs:634:28
    |
634 |         pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1};
    |                            ^^^^^^  ^^^^^^^^^^^  ^^^^^^^^  ^^^^^  ^^^^^^

ソースコード

diff #

type Fp = fp::F1000000007;

fn main() {
    let mut buf = ngtio::with_stdin();
    let n = buf.usize();
    let a = buf.vec::<u64>(n);
    let div = a
        .iter()
        .map(|&x| factorize::factorize(x))
        .collect::<Vec<_>>();
    let cnt = {
        let mut cnt = vec![Vec::new(); *a.iter().max().unwrap() as usize + 1];
        for &(p, m) in div.iter().flatten() {
            let m = m as usize;
            let vec = &mut cnt[p as usize];
            while vec.len() <= m {
                vec.push(0);
            }
            vec[m] += 1;
        }
        cnt
    };
    let prod = a.iter().map(|&x| Fp::new(x as i64)).product::<Fp>();
    let ratio = cnt
        .iter()
        .enumerate()
        .map(|(p, v)| Fp::new(p as i64).pow(weight(v)).inv())
        .product::<Fp>();
    for (div, &x) in div.iter().zip(a.iter()) {
        let ratio = ratio
            * div
                .iter()
                .copied()
                .map(|(p, m)| {
                    let mut v = cnt[p as usize].clone();
                    let orig = weight(&v);
                    v[m as usize] -= 1;
                    let new = weight(&v);
                    Fp::new(p as i64).pow(orig - new)
                })
                .product::<Fp>();
        let ans = prod * Fp::new(x as i64).inv() * (Fp::new(1) - ratio);
        println!("{}", ans);
    }
}

fn weight(v: &[u32]) -> u64 {
    v.iter()
        .enumerate()
        .map(|(i, &x)| i as u64 * x as u64)
        .sum::<u64>()
        - v.iter()
            .enumerate()
            .rev()
            .find(|&(_, &x)| x != 0)
            .map_or(0, |(pos, _)| pos as u64)
}

// factorize {{{
#[allow(dead_code)]
mod factorize {
    pub fn factorize(mut n: u64) -> Vec<(u64, u32)> {
        let mut vec = Vec::new();
        for p in 2.. {
            if n < p * p {
                break;
            }
            if n % p == 0 {
                let mut m = 0;
                while n % p == 0 {
                    n /= p;
                    m += 1;
                }
                vec.push((p, m));
            }
        }
        if n != 1 {
            vec.push((n, 1));
        }
        vec
    }
}
// }}}
// fp {{{
#[allow(dead_code)]
mod fp {
    mod arith {
        use super::{Fp, Mod};
        use std::ops::*;

        impl<T: Mod> Add for Fp<T> {
            type Output = Self;
            fn add(self, rhs: Self) -> Self {
                let res = self.0 + rhs.0;
                Self::unchecked(if T::MOD <= res { res - T::MOD } else { res })
            }
        }

        impl<T: Mod> Sub for Fp<T> {
            type Output = Self;
            fn sub(self, rhs: Self) -> Self {
                let res = self.0 - rhs.0;
                Self::unchecked(if res < 0 { res + T::MOD } else { res })
            }
        }

        impl<T: Mod> Mul for Fp<T> {
            type Output = Self;
            fn mul(self, rhs: Self) -> Self {
                Self::new(self.0 * rhs.0)
            }
        }

        #[allow(clippy::suspicious_arithmetic_impl)]
        impl<T: Mod> Div for Fp<T> {
            type Output = Self;
            fn div(self, rhs: Self) -> Self {
                self * rhs.inv()
            }
        }

        impl<M: Mod> Neg for Fp<M> {
            type Output = Self;
            fn neg(self) -> Self {
                if self.0 == 0 {
                    Self::unchecked(0)
                } else {
                    Self::unchecked(M::MOD - self.0)
                }
            }
        }

        impl<M: Mod> Neg for &Fp<M> {
            type Output = Fp<M>;
            fn neg(self) -> Self::Output {
                if self.0 == 0 {
                    Fp::unchecked(0)
                } else {
                    Fp::unchecked(M::MOD - self.0)
                }
            }
        }

        macro_rules! forward_assign_biop {
            ($(impl $trait:ident, $fn_assign:ident, $fn:ident)*) => {
                $(
                    impl<M: Mod> $trait for Fp<M> {
                        fn $fn_assign(&mut self, rhs: Self) {
                            *self = self.$fn(rhs);
                        }
                    }
                )*
            };
        }
        forward_assign_biop! {
            impl AddAssign, add_assign, add
            impl SubAssign, sub_assign, sub
            impl MulAssign, mul_assign, mul
            impl DivAssign, div_assign, div
        }

        macro_rules! forward_ref_binop {
            ($(impl $imp:ident, $method:ident)*) => {
                $(
                    impl<'a, T: Mod> $imp<Fp<T>> for &'a Fp<T> {
                        type Output = Fp<T>;
                        fn $method(self, other: Fp<T>) -> Self::Output {
                            $imp::$method(*self, other)
                        }
                    }

                    impl<'a, T: Mod> $imp<&'a Fp<T>> for Fp<T> {
                        type Output = Fp<T>;
                        fn $method(self, other: &Fp<T>) -> Self::Output {
                            $imp::$method(self, *other)
                        }
                    }

                    impl<'a, T: Mod> $imp<&'a Fp<T>> for &'a Fp<T> {
                        type Output = Fp<T>;
                        fn $method(self, other: &Fp<T>) -> Self::Output {
                            $imp::$method(*self, *other)
                        }
                    }
                )*
            };
        }
        forward_ref_binop! {
            impl Add, add
            impl Sub, sub
            impl Mul, mul
            impl Div, div
        }
    }

    use std::{
        fmt::{Debug, Display},
        hash::Hash,
        iter,
        marker::PhantomData,
        ops,
    };

    // NOTE: `crate::` がないとうまく展開できません。
    crate::define_fp!(pub F998244353, Mod998244353, 998244353);
    crate::define_fp!(pub F1000000007, Mod1000000007, 1000000007);

    #[derive(Clone, PartialEq, Copy, Eq, Hash)]
    pub struct Fp<T>(i64, PhantomData<T>);
    pub trait Mod: Debug + Clone + PartialEq + Copy + Eq + Hash {
        const MOD: i64;
    }
    impl<T: Mod> Fp<T> {
        pub fn new(mut x: i64) -> Self {
            x %= T::MOD;
            Self::unchecked(if x < 0 { x + T::MOD } else { x })
        }
        pub fn into_inner(self) -> i64 {
            self.0
        }
        pub fn r#mod() -> i64 {
            T::MOD
        }
        pub fn inv(self) -> Self {
            assert_ne!(self.0, 0, "Zero division");
            let (sign, x) = if self.0 * 2 < T::MOD {
                (1, self.0)
            } else {
                (-1, T::MOD - self.0)
            };
            let (g, _a, b) = ext_gcd(T::MOD, x);
            let ans = sign * b;
            assert_eq!(g, 1);
            Self::unchecked(if ans < 0 { ans + T::MOD } else { ans })
        }
        pub fn frac(x: i64, y: i64) -> Self {
            Fp::new(x) / Fp::new(y)
        }
        pub fn pow(mut self, mut p: u64) -> Self {
            let mut ans = Fp::new(1);
            while p != 0 {
                if p % 2 == 1 {
                    ans *= self;
                }
                self *= self;
                p /= 2;
            }
            ans
        }

        fn unchecked(x: i64) -> Self {
            Self(x, PhantomData)
        }
    }
    impl<T: Mod> iter::Sum<Fp<T>> for Fp<T> {
        fn sum<I>(iter: I) -> Self
        where
            I: iter::Iterator<Item = Fp<T>>,
        {
            iter.fold(Fp::new(0), ops::Add::add)
        }
    }

    impl<'a, T: 'a + Mod> iter::Sum<&'a Fp<T>> for Fp<T> {
        fn sum<I>(iter: I) -> Self
        where
            I: iter::Iterator<Item = &'a Fp<T>>,
        {
            iter.fold(Fp::new(0), ops::Add::add)
        }
    }

    impl<T: Mod> iter::Product<Fp<T>> for Fp<T> {
        fn product<I>(iter: I) -> Self
        where
            I: iter::Iterator<Item = Fp<T>>,
        {
            iter.fold(Self::new(1), ops::Mul::mul)
        }
    }

    impl<'a, T: 'a + Mod> iter::Product<&'a Fp<T>> for Fp<T> {
        fn product<I>(iter: I) -> Self
        where
            I: iter::Iterator<Item = &'a Fp<T>>,
        {
            iter.fold(Self::new(1), ops::Mul::mul)
        }
    }
    impl<T: Mod> Debug for Fp<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
            let (x, y, _z) = reduce(self.0, T::MOD);
            let (x, y) = match y.signum() {
                1 => (x, y),
                -1 => (-x, -y),
                _ => unreachable!(),
            };
            if y == 1 {
                write!(f, "{}", x)
            } else {
                write!(f, "{}/{}", x, y)
            }
        }
    }
    impl<T: Mod> Display for Fp<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
            write!(f, "{}", self.0)
        }
    }

    // ax + by = gcd(x, y) なる、互いに素な (a, b) を一組探して、(g, a, b) を返します。
    //
    // | 0  -x |   | y  -x | | x  0 |
    // | 1   b | = | a   b | | y  1 |
    fn ext_gcd(x: i64, y: i64) -> (i64, i64, i64) {
        let (b, g) = {
            let mut x = x;
            let mut y = y;
            let mut u = 0;
            let mut v = 1;
            while x != 0 {
                let q = y / x;
                y -= q * x;
                v -= q * u;
                std::mem::swap(&mut x, &mut y);
                std::mem::swap(&mut u, &mut v);
            }
            (v, y)
        };
        assert_eq!((g - b * y) % x, 0);
        let a = (g - b * y) / x;
        (g, a, b)
    }

    fn reduce(a: i64, m: i64) -> (i64, i64, i64) {
        if a.abs() < 10_000 {
            (a, 1, 0)
        } else {
            let mut q = m.div_euclid(a);
            let mut r = m.rem_euclid(a);
            if a <= 2 * r {
                q += 1;
                r -= a;
            }
            let (x, z, y) = reduce(r, a);
            (x, y - q * z, z)
        }
    }

    #[macro_export]
    macro_rules! define_fp {
        ($vis:vis $fp:ident, $t:ident, $mod:expr) => {
            #[derive(Debug, Clone, PartialEq, Copy, Eq, Hash)]
            $vis struct $t;
            // NOTE: `$crate::` があるとうまく展開できません。
            impl Mod for $t {
                const MOD: i64 = $mod;
            }
            // NOTE: `$crate::` があるとうまく展開できません。
            $vis type $fp = Fp<$t>;
        }
    }
}
// }}}
// ngtio {{{
#[allow(dead_code)]
mod ngtio {
    #![warn(missing_docs)]

    mod i {
        use std::{
            io::{self, BufRead},
            iter,
        };

        pub use self::multi_token::{Leaf, Parser, ParserTuple, RawTuple, Tuple, VecLen};
        pub use self::token::{Token, Usize1};

        pub fn with_stdin() -> Tokenizer<io::BufReader<io::Stdin>> {
            io::BufReader::new(io::stdin()).tokenizer()
        }

        pub fn with_str(src: &str) -> Tokenizer<&[u8]> {
            src.as_bytes().tokenizer()
        }

        pub struct Tokenizer<S: BufRead> {
            queue: Vec<String>, // FIXME: String のみにすると速そうです。
            scanner: S,
        }
        macro_rules! prim_method {
            ($name:ident: $T:ty) => {
#[allow(missing_docs)]
                pub fn $name(&mut self) -> $T {
                    <$T>::leaf().parse(self)
                }
            };
            ($name:ident) => {
                prim_method!($name: $name);
            };
        }
        macro_rules! prim_methods {
            ($name:ident: $T:ty; $($rest:tt)*) => {
                prim_method!($name:$T);
                prim_methods!($($rest)*);
            };
            ($name:ident; $($rest:tt)*) => {
                prim_method!($name);
                prim_methods!($($rest)*);
            };
            () => ()
        }
        impl<S: BufRead> Tokenizer<S> {
            pub fn token(&mut self) -> String {
                self.load();
                self.queue.pop().expect("入力が終了したのですが。")
            }
            pub fn new(scanner: S) -> Self {
                Self {
                    queue: Vec::new(),
                    scanner,
                }
            }
            fn load(&mut self) {
                while self.queue.is_empty() {
                    let mut s = String::new();
                    let length = self.scanner.read_line(&mut s).unwrap(); // 入力が UTF-8 でないときにエラーだそうです。
                    if length == 0 {
                        break;
                    }
                    self.queue = s.split_whitespace().rev().map(str::to_owned).collect();
                }
            }

            pub fn skip_line(&mut self) {
                assert!(
                    self.queue.is_empty(),
                    "行の途中で呼ばないでいただきたいです。現在のトークンキュー: {:?}",
                    &self.queue
                );
                self.load();
            }

            pub fn end(&mut self) {
                self.load();
                assert!(self.queue.is_empty(), "入力はまだあります!");
            }

            pub fn parse<T: Token>(&mut self) -> T::Output {
                T::parse(&self.token())
            }

            pub fn parse_collect<T: Token, B>(&mut self, n: usize) -> B
            where
                B: iter::FromIterator<T::Output>,
            {
                iter::repeat_with(|| self.parse::<T>()).take(n).collect()
            }

            pub fn tuple<T: RawTuple>(&mut self) -> <T::LeafTuple as Parser>::Output {
                T::leaf_tuple().parse(self)
            }

            pub fn vec<T: Token>(&mut self, len: usize) -> Vec<T::Output> {
                T::leaf().vec(len).parse(self)
            }

            pub fn vec_tuple<T: RawTuple>(
                &mut self,
                len: usize,
            ) -> Vec<<T::LeafTuple as Parser>::Output> {
                T::leaf_tuple().vec(len).parse(self)
            }

            pub fn vec2<T: Token>(&mut self, height: usize, width: usize) -> Vec<Vec<T::Output>> {
                T::leaf().vec(width).vec(height).parse(self)
            }

            pub fn vec2_tuple<T>(
                &mut self,
                height: usize,
                width: usize,
            ) -> Vec<Vec<<T::LeafTuple as Parser>::Output>>
            where
                T: RawTuple,
            {
                T::leaf_tuple().vec(width).vec(height).parse(self)
            }
            prim_methods! {
                u8; u16; u32; u64; u128; usize;
                i8; i16; i32; i64; i128; isize;
                char; string: String;
            }
        }

        mod token {
            use super::multi_token::Leaf;
            use std::{any, fmt, marker, str};

            pub trait Token: Sized {
                type Output;
                fn parse(s: &str) -> Self::Output;
                fn leaf() -> Leaf<Self> {
                    Leaf(marker::PhantomData)
                }
            }

            impl<T> Token for T
            where
                T: str::FromStr,
                <T as str::FromStr>::Err: fmt::Debug,
            {
                type Output = T;
                fn parse(s: &str) -> Self::Output {
                    s.parse().unwrap_or_else(|_| {
                        panic!("Parse error!: ({}: {})", s, any::type_name::<T>(),)
                    })
                }
            }

            pub struct Usize1 {}
            impl Token for Usize1 {
                type Output = usize;
                fn parse(s: &str) -> Self::Output {
                    usize::parse(s)
                        .checked_sub(1)
                        .expect("Parse error! (Zero substruction error of Usize1)")
                }
            }
        }

        mod multi_token {
            use super::{Token, Tokenizer};
            use std::{io::BufRead, iter, marker};

            pub trait Parser: Sized {
                type Output;
                fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> Self::Output;
                fn vec(self, len: usize) -> VecLen<Self> {
                    VecLen { len, elem: self }
                }
            }
            pub struct Leaf<T>(pub(super) marker::PhantomData<T>);
            impl<T: Token> Parser for Leaf<T> {
                type Output = T::Output;
                fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> T::Output {
                    server.parse::<T>()
                }
            }

            pub struct VecLen<T> {
                pub len: usize,
                pub elem: T,
            }
            impl<T: Parser> Parser for VecLen<T> {
                type Output = Vec<T::Output>;
                fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> Self::Output {
                    iter::repeat_with(|| self.elem.parse(server))
                        .take(self.len)
                        .collect()
                }
            }

            pub trait RawTuple {
                type LeafTuple: Parser;
                fn leaf_tuple() -> Self::LeafTuple;
            }
            pub trait ParserTuple {
                type Tuple: Parser;
                fn tuple(self) -> Self::Tuple;
            }
            pub struct Tuple<T>(pub T);
            macro_rules! impl_tuple {
                ($($t:ident: $T:ident),*) => {
                    impl<$($T),*> Parser for Tuple<($($T,)*)>
                        where
                            $($T: Parser,)*
                            {
                                type Output = ($($T::Output,)*);
#[allow(unused_variables)]
                                fn parse<S: BufRead >(&self, server: &mut Tokenizer<S>) -> Self::Output {
                                    match self {
                                        Tuple(($($t,)*)) => {
                                            ($($t.parse(server),)*)
                                        }
                                    }
                                }
                            }
                    impl<$($T: Token),*> RawTuple for ($($T,)*) {
                        type LeafTuple = Tuple<($(Leaf<$T>,)*)>;
                        fn leaf_tuple() -> Self::LeafTuple {
                            Tuple(($($T::leaf(),)*))
                        }
                    }
                    impl<$($T: Parser),*> ParserTuple for ($($T,)*) {
                        type Tuple = Tuple<($($T,)*)>;
                        fn tuple(self) -> Self::Tuple {
                            Tuple(self)
                        }
                    }
                };
            }
            impl_tuple!();
            impl_tuple!(t1: T1);
            impl_tuple!(t1: T1, t2: T2);
            impl_tuple!(t1: T1, t2: T2, t3: T3);
            impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4);
            impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5);
            impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6);
            impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7);
            impl_tuple!(
                t1: T1,
                t2: T2,
                t3: T3,
                t4: T4,
                t5: T5,
                t6: T6,
                t7: T7,
                t8: T8
            );
        }

        trait Scanner: BufRead + Sized {
            fn tokenizer(self) -> Tokenizer<Self> {
                Tokenizer::new(self)
            }
        }
        impl<R: BufRead> Scanner for R {}
    }

    pub use self::i::{with_stdin, with_str};

    pub mod prelude {
        pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1};
    }
}
// }}}
0