結果

問題 No.194 フィボナッチ数列の理解(1)
ユーザー yuppe19 😺yuppe19 😺
提出日時 2015-05-25 23:43:46
言語 Python2
(2.7.18)
結果
AC  
実行時間 376 ms / 5,000 ms
コード長 1,413 bytes
コンパイル時間 543 ms
コンパイル使用メモリ 7,040 KB
実行使用メモリ 38,016 KB
最終ジャッジ日時 2024-07-06 08:32:18
合計ジャッジ時間 7,443 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/python

mod = int(1e9) + 7

def solve1(n, k, a):
    y = 0
    for i in xrange(n):
        y = (y + a[i]) % mod
    z = y
    for i in xrange(n, k):
        a.append(z)
        y = (y + z) % mod
        z = (z + z - a[i-n]) % mod
    return a[-1], y

def matmul(A, B):
    p, q = len(A[0]), len(B)
    if p != q:
        print 'len(A[0])={} len(B)={}'.format(p, q)
        return None
    rows, cols, times = len(A), len(B[0]), len(A[0])
    res = [[0 for _ in xrange(cols)] for _ in xrange(rows)]
    for r in xrange(rows):
        for c in xrange(cols):
            res[r][c] = sum(A[r][i]*B[i][c] for i in xrange(times)) % mod
    return res

def matpow(A, n):
    sz = len(A)
    res = [[1 if i==j else 0 for j in xrange(sz)] for i in xrange(sz)]
    while n > 0:
        if n & 1:
            res = matmul(res, A)
        A = matmul(A, A)
        n >>= 1
    return res

def solve2(n, k, a):
    mat = [[0] * (n+1) for _ in xrange(n+1)]
    mat[0][0] = 2
    mat[0][-1] = -1
    for i in xrange(n):
        mat[i+1][i] = 1
    powered = matpow(mat, k-n)
    s = [0] + [sum(a[:i+1]) for i in xrange(n)]
    s = zip(s[::-1])
    res = matmul(powered, s)
    res00 = res[0][0]
    res10 = res[1][0]
    return (res00 - res10) % mod, res00 % mod

n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
if k <= 1e6:
    x, y = solve1(n, k, a)
else:
    x, y = solve2(n, k, a)
print x, y
0