Collatz polynomial

면접 대비

시간 제한0.5초메모리 제한2048 MB

요약
계수가 0 또는 1인 다항식에 대해 (x+1)을 곱하고 1을 더하는 연산과 x로 나누는 연산을 번갈아 적용하며 1이 될 때까지의 연산 횟수를 세는 문제이다.
난이도

보통10점 중 4점

유형
시뮬레이션, 구현, 비트 연산
정답자
아직 제출이 없습니다

문제

Everyone knows (or has heard of) the famous Collatz Conjecture: take a positive integer. If it is odd, multiply by 33 and add 11. If it is even, divide by 22. Repeat the process until you reach 11. Despite its simplicity, no one knows how to prove whether the sequence really always reaches 11, regardless of the initial number.

Aline, a fan of this type of curiosity, decided to create a variation using polynomials instead of numbers. To keep things simple, she works only with polynomials whose coefficients are 00 or 11, that is, each power of xx appears at most once.

The game works like this:

  • If the polynomial has a constant term (a term that does not depend on xx), Aline multiplies the polynomial by (x+1)(x + 1) and then adds 11. If any resulting coefficient equals 22, the corresponding term is discarded (note that coefficients greater than 22 cannot arise).
  • If the polynomial has no constant term, Aline divides the polynomial by xx.

This process is repeated until the polynomial reduces to P(x)=1P(x) = 1.

Consider P(x)=x3+1P(x) = x^3 + 1. In the first step there is a constant term, so we calculate:

(x3+1)⋅(x+1)+1=x4+x3+x+1+1(x^3 + 1) \cdot (x + 1) + 1 = x^4 + x^3 + x + 1 + 1.

Since the coefficient of the constant term is 22, this term is discarded, leaving:

x4+x3+xx^4 + x^3 + x.

Next, since there is no constant term, we divide by xx:

x3+x2+1x^3 + x^2 + 1.

Continuing:

  • Step 33: x4+x2+xx^4 + x^2 + x
  • Step 44: x3+x+1x^3 + x + 1
  • Step 55: x4+x3+x2x^4 + x^3 + x^2
  • Step 66: x3+x2+xx^3 + x^2 + x
  • Step 77: x2+x+1x^2 + x + 1
  • Step 88: x3x^3
  • Step 99: x2x^2
  • Step 1010: xx
  • Step 1111: 11

In total, it took 1111 operations to reach the polynomial P(x)=1P(x) = 1.

Aline needs help to study this variation of the Collatz Conjecture. Since doing these calculations manually is prone to errors, write a program that determines the number of operations needed until the polynomial becomes P(x)=1P(x) = 1.

입력

The first line contains an integer NN (0≤N≤200 ≤ N ≤ 20), indicating the degree of the polynomial.

The second line contains N+1N + 1 integers a_N,a_N−1,…,a_0a\_N , a\_{N−1}, \dots , a\_0 (each equal to 00 or 11), where a_i=1a\_i = 1 indicates that the term xix^i is present in the polynomial, and a_i=0a\_i = 0 indicates that it is not. Note that a_N=1a\_N = 1, since the degree of the polynomial is NN.

출력

Your program must output a single line, containing an integer, representing the number of operations needed until the polynomial becomes P(x)=1P(x) = 1.

예제4

  1. 예제 1

    입력
    3
    1 0 0 1
    
    예상 출력
    11
    
  2. 예제 2

    입력
    2
    1 0 1
    
    예상 출력
    6
    
  3. 예제 3

    입력
    2
    1 0 0
    
    예상 출력
    2
    
  4. 예제 4

    입력
    0
    1
    
    예상 출력
    0