<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

492. Hotel in Ves Lagos
Time limit per test: 0.25 second(s)
Memory limit: 262144 kilobytes
input: standard
output: standard



A new hotel is being built in the city of Ves Lagos. The hotel will have an infinite number of rooms (it is out of fashion to build hotels with finite numbers of rooms). The new hotel also tries to cater for superstitious guests.

The most common superstition in Ves Lagos is that the number 13 brings bad luck. Accordingly, only numbers whose decimal forms do not contain the substring "13" will be used to label the rooms in the new hotel. For example, the hotel will have rooms numbered 1, 3, 14, 31, 123, but will not have the rooms 13, 132, 913, 1308, 1313.

Let's consider the list of all room numbers, ordered increasingly. Find the N-th number in this list (members of the list are indexed from 1).

Input
The input file contains several test cases. The first line of the file contains T (1 ≤ T ≤ 100), the number of test cases. Each of the following T lines describes one test case and contains the integer N (1 ≤ N ≤ 1018).

Output
The output file should contain exactly T lines, with the i-th line containing exactly one integer, the answer for the i-th test case from the input file.

Example(s)
sample input
sample output
3
20
150
1
21
162
1

<|response|>
1. Abridged Problem Statement  
   We list all positive integers whose decimal representation does **not** contain the substring “13,” in increasing order. Given a rank N (1 ≤ N ≤ 10^18), find the N-th number in this list. There are up to T (≤ 100) such queries.

2. Key Observations  
   • N is up to 10^18, so we cannot generate the valid numbers one by one.  
   • We need a way to **count** how many valid numbers are ≤ X, for any X.  
   • If we can compute Count(X) = number of integers in [0..X] without “13,” then the N-th valid number is the smallest X such that Count(X)−1 ≥ N (we subtract one to exclude zero).  
   • Count(X) can be computed by a **digit dynamic programming** (digit‐DP) in O(L·2·2·10) where L ≈ 19 is the number of digits in X.  
   • We then find the answer by **binary searching** X in a suitable range (e.g. [1..2N]) using the monotonicity of Count(X).

3. Full Solution Approach  
   A. Digit‐DP to count valid numbers ≤ X  
     1. Let S be the decimal string of X, of length L.  
     2. Define a DP state dp[pos][lastIs1][tight], representing the number of ways to fill digits from position pos to L−1 such that we never form “13”:
        – pos: current digit index in [0..L]  
        – lastIs1: 1 if the previous digit we placed was ‘1’, else 0  
        – tight: 1 if the prefix we have built so far exactly matches the prefix of X (so the next digit d is bounded by S[pos]), else 0 (we can use 0–9 freely)  
     3. Transition at state (pos, lastIs1, tight):  
        – Determine the maximum digit we can place: up = tight ? (S[pos]−‘0’) : 9  
        – For each d in [0..up]:  
           • If lastIs1==1 and d==3, skip (that would form “13”).  
           • nextLastIs1 = (d==1) ? 1 : 0  
           • nextTight = tight && (d==up)  
           • Add dp[pos+1][nextLastIs1][nextTight] to the current state’s count.  
     4. Base case: pos==L → return 1 (an empty suffix is one valid way).  
     5. dp[0][0][1] gives Count(X) including zero. To ignore zero, subtract 1 when ranking.  

   B. Binary Search for the N-th valid number  
     1. We want the smallest X such that Count(X)−1 ≥ N.  
     2. Set lo = 1, hi = 2·N (a safe upper bound since at worst half of numbers could be invalid).  
     3. While lo ≤ hi:  
        – mid = (lo + hi) // 2  
        – If Count(mid)−1 ≥ N, record ans = mid, set hi = mid−1  
        – Else set lo = mid+1  
     4. After the loop, ans is the N-th valid number.  

   Total complexity per query: O((log N) · L · states · 10) ≈ 60 · 19 · 2·2·10 ≈ 45 600 operations, which is fast enough for T ≤ 100.

4. C++ Implementation with Detailed Comments  

```cpp
#include <bits/stdc++.h>
using namespace std;
using int64 = long long;

// Global variables for digit-DP
string bound_s;  
// dp[pos][lastIs1][tight], -1 means uncomputed
vector<array<array<int64,2>,2>> dp;

// Digit-DP recursion: count valid numbers from position 'pos' to end
// lastIs1 = 1 if previous digit was '1', else 0
// tight    = 1 if we are matching the prefix of bound_s so far
int64 dfs(int pos, int lastIs1, int tight) {
    if (pos == (int)bound_s.size()) {
        // Reached end: one valid number formed
        return 1;
    }
    int64 &res = dp[pos][lastIs1][tight];
    if (res != -1) {
        return res;
    }
    res = 0;
    int limit = tight ? (bound_s[pos] - '0') : 9;
    for (int d = 0; d <= limit; d++) {
        // Skip formation of "13"
        if (lastIs1 && d == 3) continue;
        int nextLastIs1 = (d == 1) ? 1 : 0;
        int nextTight   = (tight && (d == limit)) ? 1 : 0;
        res += dfs(pos + 1, nextLastIs1, nextTight);
    }
    return res;
}

// Count how many integers in [0..X] do NOT contain "13"
int64 countUpto(int64 X) {
    bound_s = to_string(X);
    int L = bound_s.size();
    // Initialize dp to -1
    dp.assign(L, {{{-1,-1},{-1,-1}}});
    return dfs(0, 0, 1);
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;
    while (T--) {
        int64 N;
        cin >> N;
        // Binary search for minimal X so that countUpto(X)-1 >= N
        int64 lo = 1, hi = 2 * N, ans = hi;
        while (lo <= hi) {
            int64 mid = lo + (hi - lo) / 2;
            // Subtract 1 to exclude zero from the count
            if (countUpto(mid) - 1 >= N) {
                ans = mid;
                hi = mid - 1;
            } else {
                lo = mid + 1;
            }
        }
        cout << ans << "\n";
    }
    return 0;
}
```

5. Python Implementation with Detailed Comments  

```python
import sys
sys.setrecursionlimit(10000)

def count_upto(X):
    """
    Count how many numbers in [0..X] do not contain substring '13'
    using digit DP.
    """
    s = str(X)
    L = len(s)
    # dp[pos][last1][tight]: None means uncomputed
    dp = [[[None]*2 for _ in range(2)] for __ in range(L)]
    
    def dfs(pos, last1, tight):
        # Base case: built all digits
        if pos == L:
            return 1
        if dp[pos][last1][tight] is not None:
            return dp[pos][last1][tight]
        res = 0
        limit = int(s[pos]) if tight else 9
        for d in range(limit + 1):
            # If previous was '1' and we place '3', skip
            if last1 and d == 3:
                continue
            nxt_last1 = 1 if d == 1 else 0
            nxt_tight = 1 if (tight and d == limit) else 0
            res += dfs(pos + 1, nxt_last1, nxt_tight)
        dp[pos][last1][tight] = res
        return res

    return dfs(0, 0, 1)

def find_nth(N):
    """
    Find the N-th positive integer that does not contain '13'
    by binary searching X such that count_upto(X)-1 >= N.
    """
    lo, hi = 1, 2 * N  # safe upper bound
    ans = hi
    while lo <= hi:
        mid = (lo + hi) // 2
        if count_upto(mid) - 1 >= N:
            ans = mid
            hi = mid - 1
        else:
            lo = mid + 1
    return ans

def main():
    data = sys.stdin.read().split()
    T = int(data[0])
    idx = 1
    out = []
    for _ in range(T):
        N = int(data[idx]); idx += 1
        out.append(str(find_nth(N)))
    print("\n".join(out))

if __name__ == "__main__":
    main()
```