A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:
In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.
For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.
You are given a positive integer K. Find the K-th smallest lunlun number.
Constraints
1 \leq K \leq 10^5
All values in
input are integers.
Input
Input is given from Standard Input in the following format:
K
Output
Print the answer.
Examples
Input
15
Output
23
Input
1
Output
1
Input
13
Output
21
Input
100000
Output
3234566667
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are asked: find K-th smallest lunlun number, K up to 1e5. The lunlun numbers are positive integers such that adjacent digits differ by at most 1. So we need to generate the K-th smallest such number.
We can generate in order. Since K is up to 100k, the numbers themselves could be large (the 100k-th lunlun number may have many digits). But we can generate using BFS/queue or by generating in lexicographic order from 1-digit numbers upward. Essentially we need to list numbers in increasing order (numerical order). Since numbers can have different lengths, ordering is numeric: first compare number of digits (shorter numbers are smaller unless leading zeros? But numbers have no leading zeros, so a number with fewer digits is smaller than any number with more digits if the more-digit number doesn't start with 0. So we can generate all lunlun numbers by length from 1 to whatever, and then sort within each length by numeric value (which is essentially lexicographic order because same length). So we need to generate all lunlun numbers with d digits, but only up to the K-th.
Number of lunlun numbers of length d: how many sequences of digits of length d, first digit 1-9, each adjacent diff ≤1. This is a count similar to "count of numbers where adjacent digits differ by at most 1". For each digit, we can compute using DP. For large d, counts grow but not too fast? Let's see: It's like a digit DP without upper bound, so number of d-digit lunlun numbers: sum over start digit 1-9 of number of sequences of length d starting with that digit, with transitions to digit-1, digit, digit+1 (if within 0-9). This is like a linear recurrence. The total grows roughly like something like c * λ^d where λ is the leading eigenvalue of the transition matrix (digits 0-9). Actually the transition adjacency matrix for digits: each digit i can go to i-1, i, i+1 (if within 0-9). For large d, the count for fixed start will be approximated by constant times λ^d where λ is the spectral radius. The adjacency matrix is symmetric, it's like a path graph of 10 states (0-9) with self loops and edges to neighbors. The largest eigenvalue is something like 1 + 2 cos(π/(n+1))? Actually for a path graph with loops on each node (self-loop weight 1) plus edges to neighbors weight 1, the transition matrix is tridiagonal with 1 on diagonal and 1 on sub/super diagonal for interior nodes; for endpoints, they have fewer neighbors: digit 0 can go to 0 and 1; digit 9 to 8 and 9. So the matrix is:
Row i: for i from 0 to 9.
If i=0: transitions to {0,1} => (i) itself and i+1.
If 1<=i<=8: {i-1,i,i+1}
If i=9: {8,9}
So the adjacency matrix A (size 10) counts number of ways to go from one digit to next. The number of d-digit sequences starting with a digit s is the sum over last digit of (A^{d-1}){s, t}. So total d-digit numbers = sum{s=1..9} sum_{t=0..9} (A^{d-1}){s,t}. That's essentially something like sum{i=1..9} something.
We can compute approximate growth. The eigenvalues of A? A is symmetric, so eigenvalues real. It's essentially a path with Dirichlet-like boundaries? But since each row sums to degree (except maybe). For interior nodes degree 3 (including self), endpoints degree 2. The largest eigenvalue is probably around 2.9? Let's compute quickly: The largest eigenvalue of such a matrix is less than or equal to max degree = 3, but might be less because of asymmetry? Actually it's symmetric, so spectral radius = max eigenvalue. With self-loops, we have at least eigenvalue 1. The matrix can be analyzed: For a path with reflecting boundaries? Let's attempt to compute numerically: For 10 states. The eigenvalues of a similar matrix: For a chain with nearest neighbor hops and self-loop, it's like 1+2 cos(kπ/(n+1)) for periodic? Actually for a linear chain with free ends, adjacency matrix (no self-loops) has eigenvalues 2 cos(kπ/(n+1)), k=1..n. With self-loops adding 1 to diagonal, eigenvalues become 1+2 cos(kπ/(n+1)). However that's for a chain where each vertex (except ends) is connected to two neighbors, and no self-loops. But here we have also edges to neighbors and self-loops. The adjacency with self-loops is I + adjacency of the path graph (where edges between i and i+1). For the path graph (no self-loops), eigenvalues are 2 cos(kπ/(n+1)) for k=1..n. Then adding I gives eigenvalues 1+2 cos(kπ/(n+1)). But does that hold for our matrix? Check: For path graph adjacency B: B_{i,i+1}=1, B_{i+1,i}=1, else 0. Then A = I + B? Let's check: For interior i, I + B gives self-loop 1, plus neighbors i-1 and i+1 => exactly our transitions (since it includes both neighbors). For i=0: B (path graph) would have B_{0,1}=1 and B_{1,0}=1, but B has no self-loops. So I + B for i=0 gives diagonal 1, plus neighbor 1. That matches our transitions because from digit 0 allowed transitions are {0,1}. However we also have that from digit 0 we cannot go to -1, correct. Similarly for digit 9: I + B gives {9,8} which matches. So indeed A = I + B where B is adjacency of the path graph on vertices 0..9. That is true because the path graph includes edges between consecutive digits, and B is symmetric. So eigenvalues of A are 1 + λ_B where λ_B are eigenvalues of B. For path graph on n+1 vertices (n=9? Actually vertices 0..9 inclusive => 10 vertices), eigenvalues of B are 2 cos(π k / (N+1))? Wait for path graph with N vertices, eigenvalues are 2 cos(π j / (N+1)), j=1..N. For N=10, eigenvalues = 2 cos(π j / 11), j=1..10. So eigenvalues of A: 1 + 2 cos(π j / 11), j=1..10. The largest eigenvalue occurs for j=1 where cos(π/11) is largest cos small angle: cos(π/11) ≈ cos(0.2856) ≈ 0.9595, so 1+2*0.9595 = 2.9190. Next j=2: cos(2π/11)≈ cos(0.5712)=0.8413 → 1+1.6826=2.6826; etc. So spectral radius ≈2.919. So number of d-digit lunlun numbers grows roughly like constant * (2.919)^(d-1). Since K is 1e5, we need d such that total numbers with ≤ d digits is at least 100k. Let's compute cumulative counts.
We can compute DP counts for d-digit numbers.
Alternatively, we can simply generate numbers in order using a min-heap or queue. Known technique: Since lunlun numbers are like those produced by BFS: start with 1..9, then each number X can generate children: last digit d, then append digits d-1, d, d+1 if within 0-9. If we generate in increasing order, we can use a queue: start with numbers 1..9 in a queue (or list sorted). Then repeatedly pop smallest, output, then generate its children (by appending a digit) and push them. This yields all lunlun numbers in increasing order because each number is smaller than its children (since appending a digit makes it longer, but longer numbers are larger than shorter ones only if the prefix is same? Actually, not necessarily: For example, number 10 (which is not lunlun? But in general: If we have number N, its children are N10 + d' where d' is allowed. Since N10 + d' > N (because N positive). So if we have a queue sorted by value, popping smallest will output in order. But we need to be careful: numbers of different lengths: e.g., 9 is less than 10? Actually 9 < 10, but 10 is not a lunlun? Actually 10: digits 1 and 0, absolute diff=1 => 10 is a lunlun? Yes, because 1 and 0 diff=1 ≤1. So 10 is lunlun. And 9 < 10. So if we start with numbers 1..9 and generate children, the queue will contain numbers of varying lengths. As long as we use a priority queue (min-heap) and push children, then always pop the smallest, we will get the sorted order. However, there is a nuance: we might generate numbers that are not the smallest among those not yet generated? The process is akin to generating numbers in order from a directed graph where each node has edges to larger numbers. If we start with seeds 1..9 and push them, then repeatedly pop smallest and push its successors, we will get all numbers in increasing order. This is similar to generating "lexicographically" but with numeric order. However, careful: Suppose we have number 10 (from 1 appending 0). Its children: 100? Actually children of 10 are digits: last digit 0 -> can append 0 or 1. So 100, 101. 100 is 100, and 101 is 101. Now consider number 11 (from 1 appending 1). Children: 110,111,112? Actually 11 last digit 1 -> append 0,1,2 => 110,111,112. Now 100 is 100, and 11 is 11, but 11 is smaller than 100. But 11 is already popped before 100. So it's fine. The BFS order if using a simple queue (FIFO) would not be sorted; but using a priority queue ensures we always take the smallest.
But we need to generate up to K=100k. Using a min-heap, we would push at most about K + something. Each pop we generate up to 3 children (maybe less for edges). So total operations about O(K log M) where M is heap size (≤ some). That should be fine.
But we must confirm that the process generates all lunlun numbers exactly once. Does it generate numbers like 101? 101 can be generated from 10 (append 1) or from 101? Actually 101: its prefix is 10, so it is generated by 10. But could it also be generated by 1? Not directly, because we only generate by appending one digit to an existing lunlun number. Starting from seeds 1..9, by repeatedly appending allowed digits, we generate all numbers that satisfy the condition. Indeed any lunlun number of length L can be obtained by taking its prefix of length L-1, which is also a lunlun number (since the condition holds for all adjacent pairs). So by induction, all lunlun numbers can be generated from the seeds via successive appending. And each number will be generated exactly once if we only generate from its immediate prefix. Since each number has a unique prefix (the number without its last digit), and we will generate it when we process that prefix. So yes, it's correct.
Thus we can implement: min-heap (priority queue) of integers. Initialize with 1..9. Then for i from 1 to K: pop smallest x. Then get last digit d = x % 10. For each next digit nd in {d-1, d, d+1} if 0 <= nd <= 9: push x*10 + nd. After popping K-th, output it.
But is there a risk of integer overflow? K up to 100k, the numbers could be large. In the example, for K=100000 output is 3234566667, which is about 3.2e9, fits in 64-bit (max 2^63-1 ~9e18). So 64-bit is fine.
But we need to ensure that we don't push duplicates? As argued, each number has a unique predecessor (its prefix) so it will be generated exactly once when we process that predecessor. However, could a number be generated from two different predecessors? For example, 111: prefix could be 11 (i.e., number 11) but also if we consider 111 as from 111? Actually its prefix is 11, uniquely. There's no other length L-1 prefix. So unique. So no duplicates.
One nuance: The seeds are 1..9, but what about number 0? Not positive integer. So exclude 0.
Edge case: K=1 yields 1.
So algorithm is straightforward.
But wait: Are we guaranteed that the min-heap will not exceed memory? Heap size may be up to maybe 3K? Actually each popped generates at most 3 children, and we push them. At any time, heap size will be O(number of generated but not yet popped). Since we pop K times, total pushes ≤ 3K (maybe less). So max heap size ~ 3*K = 300k, fine.
But we must be careful: The numbers generated can be huge; but we only need up to K=100k; the largest number's digit length maybe around? Let's estimate. Using the DP counts, cumulative numbers up to length d. Compute cumulative sum for d=1,2,... until exceed 1e5. Let's quickly compute counts:
Define f[d] = number of lunlun numbers with exactly d digits.
We can compute f[1] = 9 (1-9).
For d>=2, using DP: Let dp[i][digit] be count of sequences of length i ending with digit. But easier: f[d] = sum_{s=1..9} sum_{t=0..9} (A^{d-1})_{s,t}. We'll compute incrementally.
We can compute f[d] by DP loop:
Initialize an array cur[0..9] for counts for length 1: cur[d] = 1 for d=1..9 else 0. Actually for length 1, digits 1-9 are allowed, so cur[1..9] = 1.
Then for each next length, compute next array: next[nd] = sum_{d: |nd-d|<=1} cur[d]. But we need to count only numbers that start with non-zero, which is ensured because we start with cur having only digits 1-9. So after computing for length L, the sum of cur gives f[L].
So we can compute until cumulative sum >= 1e5.
Let's do quick calculation:
Initialize length 1: count=9, cumulative=9.
cur digits: index 0-9 counts: [0,1,1,1,1,1,1,1,1,1] (positions 1-9 have 1)
Now for length 2:
next[0] = cur[0]? Actually from digits d such that |0-d|<=1: d=0,1. cur[0]=0, cur[1]=1 → 1.
next[1] = from d=0,1,2: cur[0]+cur[1]+cur[2] =0+1+1=2.
next[2] = from d=1,2,3: 1+1+1=3.
next[3] = from 2,3,4: 1+1+1=3.
next[4] = 1+1+1=3 (digits 3,4,5: each count 1)
next[5] = 3 (4,5,6)
next[6] = 3 (5,6,7)
next[7] = 3 (6,7,8)
next[8] = 3 (7,8,9)
next[9] = from 8,9: cur[8]+cur[9]=1+1=2.
Check: for d=9, allowed nd=8,9 → sum=1+1=2.
So total f[2] = sum(next) = 1+2+3+3+3+3+3+3+3+2 = let's sum: 1+2=3, +3=6, +3=9, +3=12, +3=15, +3=18, +3=21, +3=24, +2=26. So 26.
Now next[0] = from d=0,1: cur[0]+cur[1] =1+2=3.
next[1] = from d=0,1,2: 1+2+3=6.
next[2] = from d=1,2,3: 2+3+3=8.
next[3] = from d=2,3,4: 3+3+3=9.
next[4] = from d=3,4,5: 3+3+3=9.
next[5] = from d=4,5,6: 3+3+3=9.
next[6] = from d=5,6,7: 3+3+3=9.
next[7] = from d=6,7,8: 3+3+3=9.
next[8] = from d=7,8,9: 3+3+2=8? Actually cur[7]=3, cur[8]=3, cur[9]=2 => 3+3+2=8.
next[9] = from d=8,9: cur[8]+cur[9] =3+2=5.
Sum = 3+6=9, +8=17, +9=26, +9=35, +9=44, +9=53, +9=62, +8=70, +5=75. So f[3]=75. Cumulative = 35+75=110.
We already exceed 100k? Actually cumulative=110 > 100, but K=100000? Wait cumulative=110 for up to 3 digits. That's 110, which is > 100 (but K up to 100000). Sorry miscalc: cumulative at length 3 = 9+26+75 = 110. That's only 110, far from 100k. Continue.
Length 4:
cur = next2: values: [3,6,8,9,9,9,9,9,8,5]
Sum: 5211+9903=15114, +13682=28796, +16346=45142, +17855=62997, +18212=81209, +17339=98548, +15060=113608, +11247=124855, +6045=130900. f[10]=130900. Cumulative up to 10 digits = 68468+130900 = 199368. That exceeds 100000. So the 100000th lunlun number is within 10-digit numbers. Specifically, cumulative up to 9 digits = 68468, so the first 68468 numbers have at most 9 digits. The next 100000-68468 = 31532 numbers among the 10-digit numbers. So the answer is the 31532nd 10-digit lunlun number. So length 10. So numbers up to about 10 digits, max 10 digits, which is fine for 64-bit.
Thus heap method with K up to 100k will generate numbers up to length maybe 10 or 11, so heap size manageable.
Alternative approach: generate by DP lexicographic order? But heap is simple.
But we need to be careful: The heap will contain numbers of varying lengths; since the numbers increase, the heap will contain many numbers, but at most ~3*K, which is fine. However, note that the generation process will produce numbers beyond the K-th because we might push children of the (K-1)-th popped numbers that are less than the K-th? Actually we only need to pop K numbers. After popping the K-th, we output. The heap may still contain extra numbers, but that's fine. The heap will contain numbers of length up to maybe 11 or 12, but still limited.
But we must ensure that we do not overflow the heap with too many numbers? For K=100k, we might push about 3*100k = 300k numbers, each as 64-bit integer. That's fine.
Now potential pitfalls: Since we are pushing numbers onto a min-heap, we must be cautious that the numbers could be large and the heap operations O(log N). For N=300k, log2(300k)~19, times 300k ~6e6 operations, fine.
So implementation straightforward.
But is there any duplicate generation? As argued, no. However, consider number like 1: seeds 1. Children: 10,11,12. Then when we pop 10, children: 100,101,102? etc. But note that 101 could also be generated from 10 (append 1) and also from 101? No, only from 10. So unique.
But what about numbers like 111? generated from 11 (append 1) but also from 111? Not. So unique.
Thus algorithm works.
Edge case: Starting seeds: should we include 0? No, positive integers only.
Now, is there any possibility of generating numbers with leading zeros? When we generate children, we append digits to an existing number. The existing number has no leading zeros because seeds are 1-9 and appending digits can be 0, so the child could have a digit 0 as its last digit, but it's okay; the number may contain internal zeros, but the first digit is non-zero. So fine.
Implementation in Python:
Use heapq.
Initialize heap with list(range(1,10))
For i in range(K):
x = heapq.heappop(heap)
d = x % 10
for nd in [d-1, d, d+1]:
if 0 <= nd <= 9:
heapq.heappush(heap, x*10 + nd)
Print x after loop.
But careful: The above will pop K numbers, and after popping the K-th, we have x as the K-th. So we can break after K pops and print.
One nuance: For K=1, we pop 1 and then push 10,11,12? Actually after popping, we push children. But we only need to pop K numbers, so after popping the K-th, we don't need to push its children. But we could push anyway; it doesn't matter because we stop after output. However, we need to be careful: We are in a loop that pops K times; inside the loop we pop and then push children. For the K-th pop, we still push its children, but we won't use them. That's okay. But we could optimize by not pushing children after the K-th pop. But not needed.
Now, test with given examples:
K=15: Let's compute manually perhaps? The output is 23. Let's simulate: Seeds: 1,2,3,4,5,6,7,8,9.
Pop order: 1 (K=1), push 10,11,12.
Heap now: 2,3,4,5,6,7,8,9,10,11,12. (min 2)
Pop 2 (K=2), push 21,22,23.
Heap: 3,4,5,6,7,8,9,10,11,12,21,22,23.
Pop 3 (K=3), push 32,33,34.
Heap: 4,5,6,7,8,9,10,11,12,21,22,23,32,33,34.
Pop 4 (K=4), push 43,44,45.
Heap: 5,6,7,8,9,10,11,12,21,22,23,32,33,34,43,44,45.
Pop 5 (K=5), push 54,55,56.
Pop 6 (K=6), push 65,66,67.
Pop 7 (K=7), push 76,77,78.
Pop 8 (K=8), push 87,88,89.
Pop 9 (K=9), push 98,99,90? Actually last digit 9 => push 98,99, (9-1=8 => 98? Actually 910+8=98, 910+9=99, and 9*10+10? No, d+1=10 not allowed. So only 98,99.
Heap now contains many numbers. Let's list order after popping first 9:
Current heap (min values): 10,11,12,21,22,23,32,33,34,43,44,45,54,55,56,65,66,67,76,77,78,87,88,89,98,99,... plus others from pushes.
Now pop 10 (K=10), push from 10: digits 0 => allowed 0,1 => push 100,101.
Pop 11 (K=11), push 110,111,112.
Pop 12 (K=12), push 121,122,123? Actually last digit 2 => push 121? Wait 1210+1=121, 1210+2=122, 12*10+3=123.
Pop 13 (K=13): The next smallest? Let's see heap: after popping 10,11,12, heap includes: 21,22,23,32,... etc. But maybe 21 is next? Actually after K=10 popped 10, heap min might be 21? Let's check: after popping 10, heap had numbers: 11,12,21,22,23,... But we then popped 11 and 12. So after K=12, we have popped: 1,2,3,4,5,6,7,8,9,10,11,12. Next smallest among remaining: likely 21. So K=13 should be 21. Example says for K=13 output is 21, which matches. Then K=14 would be 22, K=15 would be 23? But example input 15 output 23. So our simulation: after popping 12, heap includes 21,22,23,... So K=13 -> 21, K=14 -> 22, K=15 -> 23. Yes matches.
So heap method works.
Now, K up to 100000, we need to be efficient in Python. Using heapq with integers is fine. However, we must be careful that we may push huge numbers, but that's okay.
We could also use BFS with a queue but need order, so heap is natural.
But maybe we can implement using deque and generate in order without heap? Since the numbers are generated in a kind of "like sorted" if we use a queue but not exactly, we need to simulate merging streams. However heap is simple.
Potential memory: storing up to maybe 500k integers. That's fine.
Edge cases: K=1 => output 1; K=2 => output 2? Actually seeds: pop 1, then 2. So 2. So seems correct.
Now, confirm for K=100000, output 3234566667. We'll test later.
Thus solution: use a min-heap.
However, there is another nuance: In Python, heapq is a min-heap. But we need to ensure we do not run into recursion or stack issues. Not.
Now, think about performance: For K=100000, each pop O(log N) ~ log(300k) ~ 19, total ~2 million operations, plus pushes. That's fine.
But could we do it even simpler? Since we know that the numbers up to length 10 are within 200k total, we could generate all lunlun numbers up to length 10 using recursion/backtracking and then sort them. The total count up to length 10 is cumulative 199368 (as computed) > 100k, so we could generate all numbers with up to 10 digits, then sort and pick K-th. That would be about 200k numbers, sorting would be O(N log N) with N=200k, fine. But generating all lunlun numbers with up to 10 digits via DFS could be done. But the heap method is simpler.
But we need to be careful: The heap method might generate numbers beyond length 10? For K=100000, we stop after popping 100000 numbers. The 100000th number is a 10-digit number, as computed. The heap will contain also numbers of length 10 and maybe some length 11 (since when we pop a 9-digit number, we push its children which are 10-digit; when we pop a 10-digit number, we push 11-digit numbers. But we only pop up to K=100000, and the 100000th number is a 10-digit number. We might have popped some 10-digit numbers before that. But when we pop a 10-digit number before we reach K, we might push its 11-digit children. So the heap might contain some 11-digit numbers by the time we finish. But that's okay; they won't be popped if we stop at K (since the K-th is popped). The heap may have size around maybe 300k but okay.
But we must consider that we might push extremely large numbers (like 11-digit) but they are within 64-bit.
Now, test with K=100000: the answer given is 3234566667, which is 10-digit (3,234,566,667). That is indeed 10-digit.
Thus our heap method should output the same.
But we can verify that the 31532nd 10-digit lunlun number is 3234566667? We'll trust.
One more nuance: The heap method ensures numeric order because we always pop the smallest. But does it guarantee that if two numbers have the same numeric value? That cannot happen because they are distinct numbers. So fine.
Thus solution is straightforward.
Now, possible improvement: Instead of heap, we could generate all numbers up to length L and sort. Since L=10, we can generate via DFS/backtracking: for length d from 1 to 10, for first digit 1-9, then recursively generate next digits with diff <=1. Collect all numbers in a list. Then sort. That would generate at most 199k numbers, sort is quick. Actually we need only up to K-th, we can generate numbers of length up to necessary (i.e., while cumulative < K, generate next length). Then we generate numbers of that length and sort them, then pick (K - cumulative_before)th. That avoids heap. Might be simpler in some languages but heap is fine.
Let's consider if we want to implement the DP/backtrack approach: we can compute cumulative counts to determine the exact length of K-th number, then generate all numbers of that length in order (by recursion) and then pick the required index. Since we know the count of numbers of length L, we can determine L. Then we need to generate the numbers of length L in increasing order. To generate in increasing order, we can do a DFS that builds numbers digit by digit, but we need to generate in numeric order. Since the digits are generated lexicographically if we iterate first digit from 1 to 9, and for each, recursively generate digits with allowed transitions, the resulting sequence will be in numeric order because for same length, numeric order corresponds to lexicographic order of digit strings. So we can generate all length-L lunlun numbers in sorted order via recursion/backtracking. Then we can directly get the (K - cumulative_{L-1})th number from that list. That would be O(f[L]) which at most 130k for L=10, which is fine. This method avoids heap and is deterministic. It also avoids generating numbers of shorter lengths that we don't need (though we need to compute cumulative counts to find L). But we already computed cumulative counts up to length L-1 to find L; we can compute those counts via DP, then generate numbers of length L. That's also simple.
But note: K up to 1e5, and we can precompute DP counts and then generate using recursion. That approach might be safer and not rely on heap with possible large memory? Actually heap is also safe. But whichever is fine.
I'll choose heap because it's straightforward and I can implement quickly.
But there is a subtlety: In Python, integers are unbounded but we only use 64-bit. The heap will contain numbers as Python ints, which are objects and overhead might be significant but for 300k it's fine.
I'll code:
import heapq
def solve():
import sys
K = int(sys.stdin.readline())
if K <= 9:
print(K) # but better to use general method; but K=1 gives 1, works anyway.
return
heap = list(range(1,10))
heapq.heapify(heap)
for _ in range(K-1):
x = heapq.heappop(heap)
d = x % 10
for nd in (d-1, d, d+1):
if 0 <= nd <= 9:
heapq.heappush(heap, x*10 + nd)
ans = heapq.heappop(heap)
print(ans)
But careful: The loop above does K-1 pops then one extra pop to get K-th? Actually we start with heap having 9 numbers. We need to pop K numbers. If we loop K times: for i in range(K): x = heappop; if i == K-1: ans = x; break else: generate children. That's fine.
Simplify: for i in range(K):
x = heapq.heappop(heap)
if i == K-1:
print(x)
return
d = x%10
for nd in (d-1,d,d+1):
if 0 <= nd <= 9:
heapq.heappush(heap, x*10+nd)
But we may need to generate children even for the K-th? No, we don't need to. So we break after printing.
But careful: For K=1, we shouldn't generate children from 1. So that's fine.
Implementation details: we can also do:
heap = [i for i in range(1,10)]
heapq.heapify(heap)
for _ in range(K-1):
x = heapq.heappop(heap)
d = x%10
for nd in (d-1,d,d+1):
if nd>=0 and nd<=9:
heapq.heappush(heap, x*10+nd)
ans = heapq.heappop(heap)
print(ans)
That works for K>=1. For K=1, the loop runs 0 times, then we pop ans = heapq.heappop(heap) which would be 1. That's correct. But then we have not generated children from 1. That's okay. However, we then printed ans without generating children. That's fine.
But note: After popping ans, we have left some numbers in heap? No issue.
But need to ensure for K=1, heap after initialization has [1..9]. We pop one and get 1, print, done. Good.
For K=2, loop runs once: pop x=1, generate children (10,11,12) push them. Then after loop, pop ans = heapq.heappop(heap). Now heap contains [2,3,4,5,6,7,8,9,10,11,12]. The smallest is 2, so ans=2. That's correct.
Thus simple.
Time complexity: O(K log M) where M ~ up to 3K.
Memory: O(M).
Now, test with given examples.
Example1: K=15 -> should output 23. Our simulation gave 23. Good.
Example2: K=1 -> output 1.
Example3: K=13 -> output 21. Our simulation gave 21 as the 13th? Actually after popping 12 numbers, the heap's smallest is 21, so 13th is 21. Good.
Now, we need to handle input reading and output.
Thus final solution.
But before finalizing, consider if there is any problem with the heap method regarding overflow or negative numbers? No.
Alternative approach using BFS with queue would not guarantee order.
Thus answer is straightforward.
Now, I might consider potential pitfalls: The heap will contain numbers of varying lengths, but as we generate children, numbers increase, so the heap's size may become larger than 3*K? Actually each popped number generates at most 3 children, but we push them. So total pushes = sum_{i=1}^{K-1} (degree of popped number). Degree could be up to 3, but sometimes less (when last digit is 0 or 9). So total pushes ≤ 3(K-1). So heap size at any time ≤ initial size (9) + pushes - (pops before) roughly ≤ 9 + 3(K-1) - (K-1) = 9 + 2(K-1) = O(2K). At K=100000, heap size ~200k, fine.
Thus solution is efficient.
Now, implement.
Edge Cases: K=100000, we need to generate many numbers, but Python should handle.
Potential optimization: Use collections.deque and maintain multiple queues for each digit? Not needed.
Now, let's also verify with K=100000 output: 3234566667. We can test with code if possible but not here.
One might worry about the order: Are we sure that popping from min-heap yields numbers in increasing order? Since all numbers are positive and distinct, yes. But must ensure that when we push new numbers, they are larger than the popped one because we multiply by 10 and add a digit (0-9). Multiplying by 10 and adding yields a number > original if original > 0? For x>0, x10+nd >= x10 >= 10 > x for x>=1? Actually if x=1, x*10+nd >=10 >1. So yes, children are strictly larger than parent. Therefore, when we pop the smallest element from heap, all children of previously popped numbers are larger than the current smallest? Not necessarily: Suppose we popped a number a, and generated children c1, c2, c3. Those children are larger than a. But there could be other numbers already in the heap that are smaller than some children. However, the heap always contains the smallest among all not-yet-popped numbers. Since each child is larger than its parent, and parent has already been popped (which was the smallest at that time), it is possible that there are other numbers in the heap that are smaller than this child. But that's okay; the heap will pop them in order. Since we always pop the current minimum, the sequence will be increasing. This is standard for generating numbers in order from a set of seeds and a monotone expansion operator.
More formally, it's analogous to Dijkstra on a graph where edge weights are positive (the cost of going from parent to child is increase). Since all children are larger, we can use a priority queue to traverse in increasing order.
Thus correctness is ensured.
Now, we should also consider that we might generate the same number from different paths? As argued, each number has a unique immediate predecessor (its prefix) so duplicates cannot occur. But let's verify: Could there be a scenario where a number could be formed by two different prefixes? For example, number 101: prefix is 10 (since 101//10=10). Could also be formed from 101? No. Unique. For numbers with trailing zeros? e.g., 110: prefix 11. Could also be formed from 1? Not. So unique.
Thus no duplicates.
So solution is correct.
Now, alternative solutions: Use BFS with multiple queues? Not needed.
Thus final answer.
But we need to produce code. We'll produce a function solve().
Potential pitfalls: For large K, recursion is not used.
We'll use sys.stdin.readline for fast input.
Now, I'll produce final explanation.
But I should also note that the problem appears in AtCoder (ABC 176 D? Actually problem "Lunlun Number" from AtCoder ABC 176? No, maybe from ABC 215? Actually it's AtCoder problem "abc146_d"? Not sure. Anyway.
Thus final.
Let's write final solution:
code
import heapq
def solve():
import sys
K = int(sys.stdin.readline())
heap = list(range(1, 10))
heapq.heapify(heap)
for _ in range(K-1):
x = heapq.heappop(heap)
d = x % 10
for nd in (d-1, d, d+1):
if 0 <= nd <= 9:
heapq.heappush(heap, x*10 + nd)
print(heapq.heappop(heap))
But there is a subtle bug: For K=1, the loop for _ in range(K-1) runs 0 times, then we pop and print heap[0], which is 1. But after that, we haven't consumed the first element? Actually we popped it after the loop, so we popped one extra. For K=1, we should not pop after the loop; we should directly output the smallest without popping extra? Let's analyze: After initialization, heap has numbers 1..9. The first (and only) number we need is the smallest, which is 1. In our code, we do for _ in range(K-1): which does nothing. Then we do heapq.heappop(heap) to get the answer. That pops 1 from heap and prints. That's fine, because we want the 1st smallest. So for K=1, it works.
But for K>1, the loop pops K-1 numbers, generating children for each. Then after loop, we pop the K-th number and print. That is correct because the loop pops exactly K-1 numbers, and then we pop the K-th.
So code is correct.
But we must ensure that after the loop, the heap still contains the K-th smallest; because we popped the first K-1 smallest numbers, the K-th smallest is now the smallest in the heap. So popping it gives the answer.
Thus final code.
Now, we should maybe use faster I/O? Not necessary.
But note: In Python, using heapq with integers is fine.
Thus final answer.
We should also include explanation in the final output.
Now, produce final message.
```python
import sys
import heapq
def solve() -> None:
K = int(sys.stdin.readline())
code
# initialise the min‑heap with all one‑digit lunlun numbers
heap = list(range(1, 10))
heapq.heapify(heap)
# extract the first K-1 numbers and generate their children
for _ in range(K - 1):
x = heapq.heappop(heap)
last = x % 10
for nd in (last - 1, last, last + 1):
if 0 <= nd <= 9:
heapq.heappush(heap, x * 10 + nd)
# the K‑th smallest is now the smallest element of the heap
ans = heapq.heappop(heap)
print(ans)