Under construction

Still being built. Things may change

Nested Palindrome

Time limit2sMemory limit128 MB

Summary
Fill each question mark with a digit to build the k-th smallest nested palindrome with no equal adjacent digits, or print -1.
Level

Medium7 of 10

Topics
Recursion, Combinatorics, String
Solved
No attempts yet

Problem

A palindrome reads the same forward and backward. Kkung likes one special kind of palindrome, which he calls a nested palindrome. A number is a nested palindrome when all three conditions hold.

  • The whole number is a palindrome.
  • Cut the number in half, and the front half is again a nested palindrome. When the number of digits is odd, drop the single middle digit before cutting. A one-digit number has an empty front half, so it is always a nested palindrome.
  • No two adjacent digits are equal.

Kkung wrote down one nested palindrome, and its first digit is not 0. He then covered some of the digits with question marks. Fill every question mark with a single digit and collect every nested palindrome you can make that way. Kkung wants the kk-th smallest of them. He may have written the number wrong, so it can happen that no filling produces a nested palindrome.

Input

The input holds several test cases, and each test case is two lines.

The first line has an integer kk (1≤k≤10181 \le k \le 10^{18}). The second line has a string of length 11 to 1000010000 that consists only of the digits 0 to 9 and question marks.

The last line of the input is a single 0, and it is not a test case.

Output

For each test case, print the nested palindrome Kkung is looking for on its own line. If fewer than kk nested palindromes can be made from the question marks, print -1.

Examples2

  1. Example 1

    Input
    1
    1?1
    1
    ?3?
    1
    ?1?
    55
    ???
    55
    1?1
    3
    0?0
    0
    
    Expected output
    101
    131
    212
    707
    -1
    -1
    
  2. Example 2

    Input
    1
    ?
    2
    1?1
    1
    ??
    0
    
    Expected output
    1
    121
    -1