-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA_321_like_Checker.cpp
More file actions
78 lines (60 loc) · 1.92 KB
/
A_321_like_Checker.cpp
File metadata and controls
78 lines (60 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
const int MAX_DIGITS = 10;
// DP table to store the count of 321-like numbers
long long dp[MAX_DIGITS][MAX_DIGITS][MAX_DIGITS];
// Function to count the number of 321-like numbers with the given digits
long long count321Numbers(int pos, int num3, int num2, bool tight, const vector<int>& digits) {
if (pos == 0) {
return 1; // Reached the end, a 321-like number is found
}
if (dp[pos][num3][num2] != -1 && !tight) {
return dp[pos][num3][num2];
}
int upper_limit = tight ? digits[pos] : 9;
long long count = 0;
for (int digit = 0; digit <= upper_limit; ++digit) {
if (digit == 3 && num2 > 0) {
continue; // Skip numbers with consecutive 3's
}
if (digit == 2 && num3 > 0) {
continue; // Skip numbers with consecutive 32's
}
int new_num3 = (digit == 3) ? num2 + 1 : 0;
int new_num2 = (digit == 2) ? num3 + 1 : 0;
bool new_tight = (digit == digits[pos]) ? tight : false;
count += count321Numbers(pos - 1, new_num3, new_num2, new_tight, digits);
}
if (!tight) {
dp[pos][num3][num2] = count;
}
return count;
}
// Function to find the k-th smallest 321-like number
long long findKth321Number(int k) {
if (k <= 0) {
return -1; // Invalid input
}
vector<int> digits;
while (k > 0) {
digits.push_back(k % 10);
k /= 10;
}
memset(dp, -1, sizeof(dp));
return count321Numbers(digits.size() - 1, 0, 0, true, digits);
}
int main() {
int k;
cout << "Enter the value of k: ";
cin >> k;
long long result = findKth321Number(k);
if (result != -1) {
cout << "The " << k << "-th smallest 321-like number is: " << result << endl;
} else {
cout << "Invalid input or k is less than 1." << endl;
}
return 0;
}