This page is still under construction.

Parts of this page are still being built. What you see may change.

Fibonacci Sums

Time limit1sMemory limit128 MB

Summary
Given two Zeckendorf representations of positive integers, compute the Zeckendorf representation of their sum.
Level

Hard8 of 10

Topics
Greedy, Math, Number theory, Implementation
Solved
No attempts yet

Problem

The Fibonacci numbers are an integer sequence defined as follows: F0=1F_0 = 1, F1=1F_1 = 1, and Fi=Fi−2+Fi−1F_i = F_{i-2} + F_{i-1} for i≥2i \ge 2. The first few terms of the sequence are 1,1,2,3,5,8,…1, 1, 2, 3, 5, 8, \dots

The computer scientist Byteazar is building an unusual computer in which numbers are represented in the Fibonacci system: a bit string (b1,b2,…,bn)(b_1, b_2, \dots, b_n) denotes the number b1F1+b2F2+⋯+bnFnb_1 F_1 + b_2 F_2 + \dots + b_n F_n. (Note that F0F_0 is not used.) Unfortunately, this representation is not unique: the same number can have several representations. For example, the number 4242 can be written as (0,0,0,0,1,0,0,1)(0,0,0,0,1,0,0,1), (0,0,0,0,1,1,1,0)(0,0,0,0,1,1,1,0), or (1,1,0,1,0,1,1)(1,1,0,1,0,1,1). For this reason, Byteazar restricts himself to representations satisfying the following two conditions:

  • if n>1n > 1, then bn=1b_n = 1; that is, the representation has no leading zeros.
  • if bi=1b_i = 1, then bi+1=0b_{i+1} = 0 (for i=1,…,n−1i = 1, \dots, n-1); that is, the representation contains no two (or more) consecutive ones.

Byteazar is having trouble implementing addition. Help him!

Write a program that:

  • reads from standard input the representations of two positive integers, and
  • computes and writes to standard output the representation of their sum.

Input

The input contains the Fibonacci representations (satisfying the conditions above) of two positive integers xx and yy — one on the first line, the other on the second line. Each representation is a sequence of non-negative integers separated by single spaces. The first number on the line is the length nn of the representation, where 1≤n≤1 000 0001 \le n \le 1\,000\,000. It is followed by nn zeros and/or ones.

Output

On the only line of output, write the Fibonacci representation (satisfying the conditions above) of the sum x+yx + y. The representation must be a sequence of non-negative integers separated by single spaces, as described in the Input section. The first number on the line is the length nn of the representation, where 1≤n≤1 000 0001 \le n \le 1\,000\,000, followed by nn zeros and/or ones.

Examples3

  1. Example 1

    Input
    4 0 1 0 1
    5 0 1 0 0 1
    
    Expected output
    6 1 0 1 0 0 1
    
  2. Example 2

    Input
    1 1
    1 1
    
    Expected output
    2 0 1
    
  3. Example 3

    Input
    1 1
    2 0 1
    
    Expected output
    3 0 0 1