結果

問題 No.665 Bernoulli Bernoulli
ユーザー pekempeypekempey
提出日時 2018-03-10 14:38:29
言語 Haskell
(9.8.2)
結果
AC  
実行時間 42 ms / 2,000 ms
コード長 1,346 bytes
コンパイル時間 5,214 ms
コンパイル使用メモリ 179,248 KB
実行使用メモリ 12,824 KB
最終ジャッジ日時 2023-08-03 13:09:05
合計ジャッジ時間 7,206 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,776 KB
testcase_01 AC 2 ms
6,864 KB
testcase_02 AC 12 ms
11,568 KB
testcase_03 AC 42 ms
12,808 KB
testcase_04 AC 42 ms
12,244 KB
testcase_05 AC 42 ms
12,180 KB
testcase_06 AC 42 ms
12,284 KB
testcase_07 AC 42 ms
12,188 KB
testcase_08 AC 42 ms
12,172 KB
testcase_09 AC 42 ms
12,268 KB
testcase_10 AC 42 ms
12,108 KB
testcase_11 AC 42 ms
12,772 KB
testcase_12 AC 42 ms
12,248 KB
testcase_13 AC 42 ms
12,752 KB
testcase_14 AC 42 ms
12,824 KB
testcase_15 AC 42 ms
12,256 KB
testcase_16 AC 42 ms
12,268 KB
testcase_17 AC 42 ms
12,184 KB
testcase_18 AC 42 ms
12,208 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Loaded package environment from /home/judge/.ghc/x86_64-linux-9.6.1/environments/default
[1 of 2] Compiling Main             ( Main.hs, Main.o )
[2 of 2] Linking a.out

ソースコード

diff #

import Data.List (foldl', scanl)
import Data.Int (Int)

md :: Int
md = 10^9 + 7

modadd :: Int -> Int -> Int
modadd a b = (a + b) `mod` md 

modmul :: Int -> Int -> Int
modmul a b = a * b `mod` md

modpow :: Int -> Int -> Int
modpow a b
  | b == 0 = 1
  | odd b = a * modpow a (b - 1) `mod` md
  | otherwise = modpow (a * a `mod` md) (b `div` 2)

modinv :: Int -> Int
modinv a = modpow a (md - 2)

--     (x-1)(x-2)...(x-n+1)
-- ------------------------ a[0] + ...
--     (0-1)(0-2)...(0-n+1)

lagrange :: [Int] -> Int -> Int
lagrange a x
  | x < n = a !! x
  | otherwise = let (sm, _, _, _) = foldl' f (0, 0, 1, q) a
                in sm
  where
    n = length a
    p = foldl' modmul 1 [(x - i) | i <- [0..n-1]]
    q = foldl' modmul 1 [-i | i <- [1..n-1]]
    f :: (Int, Int, Int, Int) -> Int -> (Int, Int, Int, Int)
    f (sm, k, l, r) ak = (nextSm, k + 1, nextL, nextR)
      where 
        nextSm = modadd sm $ ak `modmul` p `modmul` modinv (l `modmul` r `modmul` (x - k))
        nextL = l `modmul` (k + 1)
        nextR = r `modmul` negate (modinv (n - 1 - k))

computeSmall :: Int -> [Int]
computeSmall k = scanl f 0 [1..k + 2]
  where
    f s x = s `modadd` (modpow x k)

solve :: Int -> Int -> Int
solve n k = lagrange (computeSmall k) (n `mod` md)

main = do
  [n, k] <- map read . words <$> getLine :: IO [Int]
  print $ solve n k

0