Fibonacci Sums (Codeforces 126D)
Tags: Math, dp

Fibonacci numbers have the following form:F1 = 1,  F2 = 2,  Fi = Fi - 1 + Fi - 2, i > 2.Let's consider some non-empty set S = {s1, s2, ..., sk}, consisting of different Fibonacci numbers. Let's find the sum of values of this set's elements:Let's call the set S a number n's decomposition into Fibonacci sum. It's easy to see that several numbers have several decompositions into Fibonacci sum. For example, for 13 we have 13, 5 + 8, 2 + 3 + 8 — three decompositions, and for 16: 3 + 13, 1 + 2 + 13, 3 + 5 + 8, 1 + 2 + 5 + 8 — four decompositions.By the given number n determine the number of its possible different decompositions into Fibonacci sum.

Input: The first line contains an integer t — the number of tests (1 ≤ t ≤ 105). Each of the following t lines contains one test.Each test is an integer n (1 ≤ n ≤ 1018).Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.

Output: For each input data test print a single number on a single line — the answer to the problem.

Note: Two decompositions are different if there exists a number that is contained in the first decomposition, but is not contained in the second one. Decompositions that differ only in the order of summands are considered equal.

Sample Inputs:
2
13
16

Sample Outputs:
3
4

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
ans = []
f = [1, 2]
inf = pow(10, 18) + 1
while f[-1] + f[-2] < inf:
    f.append(f[-1] + f[-2])
l = len(f)
for _ in range(t):
    n = int(input())
    x = []
    for i in range(l - 1, -1, -1):
        if n >= f[i]:
            n -= f[i]
            x.append(i)
    x.append(-1)
    x.reverse()
    m = len(x)
    (dp1, dp2) = ([0] * m, [0] * m)
    dp1[0] = 1
    for i in range(1, m):
        d = x[i] - x[i - 1] - 1
        (d1, d2) = (d // 2, (d + 1) // 2)
        dp1[i] = dp1[i - 1] + dp2[i - 1]
        dp2[i] = dp1[i - 1] * d1 + dp2[i - 1] * d2
    ans0 = dp1[-1] + dp2[-1]
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
ans = []
f = [1, 2]
inf = pow(10, 18) + 1
while f[-1] + f[-2] < inf:
    f.append(f[-1] + f[-2])
l = len(f)
for _ in range(t):
    n = int(input())
    x = []
    for i in range(l - 1, -1, -1):
        if n >= f[i]:
            n -= f[i]
            x.append(i)
    x.append(-1)
    x.reverse()
    m = len(x)
    (dp1, dp2) = ([0] * m, [0] * m)
    dp1[0] = 1
    for i in range(1, m):
        d = x[i] - x[i - 1] - 1
        (d1, d2) = (d // 2, (d + 1) // 2)
        dp1[i] = dp1[i - 1] + dp2[i - 1]
        dp2[i] = dp1[i - 1] * d1 + dp2[i - 1] * d2
    ans0 = dp1[-1] + dp2[-1]
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        inf = float('inf')

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import math
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        class FastIO(IOBase):
            newlines = 0

            def __init__(self, file):
                self._fd = file.fileno()
                self.buffer = BytesIO()
                self.writable = 'x' in file.mode or 'r' not in file.mode
                self.write = self.buffer.write if self.writable else None

            def read(self):
                while True:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    if not b:
                        break
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines = 0
                return self.buffer.read()

            def readline(self):
                while self.newlines == 0:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    self.newlines = b.count(b'\n') + (not b)
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines -= 1
                return self.buffer.readline()

            def flush(self):
                if self.writable:
                    os.write(self._fd, self.buffer.getvalue())
                    (self.buffer.truncate(0), self.buffer.seek(0))

        class IOWrapper(IOBase):

            def __init__(self, file):
                self.buffer = FastIO(file)
                self.flush = self.buffer.flush
                self.writable = self.buffer.writable
                self.write = lambda s: self.buffer.write(s.encode('ascii'))
                self.read = lambda : self.buffer.read().decode('ascii')
                self.readline = lambda : self.buffer.readline().decode('ascii')
        sys.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')
fibs = [1, 2]
while fibs[-1] < 10 ** 18:
    fibs.append(fibs[-1] + fibs[-2])
fibs.pop()
k = len(fibs)

def main():
    n = II()
    tmp = []
    for i in range(k - 1, -1, -1):
        if n >= fibs[i]:
            n -= fibs[i]
            tmp.append(i)
    tmp.append(-1)
    tmp.reverse()
    m = len(tmp)
    (dp1, dp2) = ([0] * m, [0] * m)
    dp1[0] = 1
    for i in range(1, m):
        d = tmp[i] - tmp[i - 1] - 1
        d1 = d // 2
        d2 = d - d1
        dp1[i] = dp1[i - 1] + dp2[i - 1]
        dp2[i] = dp1[i - 1] * d1 + dp2[i - 1] * d2
    print(dp1[-1] + dp2[-1])
    return
t = II()
for _ in range(t):
    main()