Nearest Beautiful Number (easy version)

Nearest Beautiful Number (easy version)

Created by LXC on Mon Apr 8 11:45:30 2024

https://codeforces.com/problemset/problem/1560/F1

ranting: 1900

tag: binary search, bitmasks, brute force, constructive algorithms, dfs and similar, greedy

problem

给定数据组数 $t$,每组数据包含正整数 $n$、$k$,求满足 $x\geq n$ 的最小正整数 $x$,使 $x$ 是个 $k$-beautiful 数。

一个正整数是个 $k$-beautiful 数,当且仅当其无前导零的十进制数值表示中,不同的数字不超过 $k$ 个。

数据满足 $1 \leq t \leq 10^4$,$1 \leq n \leq 10^9$,$1 \leq k \leq 2$。

solution

从高位开始枚举,对于$n_i$尝试改变为$9,8,…,n_i+1$,对于$n_i$以下的低位我们可以将他们改为同一个值。(如果高位已出现k种不同的值,就选k个中最小的一个,否则就选择0)

code

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

#include <bits/stdc++.h>
// #define SINGLE_INPUT
#define ll long long
#define ull unsigned long long
#define N 500005
#define MOD 998244353
using namespace std;

random_device seed;
ranlux48 engine(seed());
int random(int l, int r) {
uniform_int_distribution<> distrib(l, r);
return distrib(engine);
}
template<class t,class u> ostream& operator<<(ostream& os,const pair<t,u>& p) {
return os<<'['<<p.first<<", "<<p.second<<']';
}
template<class t> ostream& operator<<(ostream& os,const vector<t>& v) {
os<<'['; int s = 1;
for(auto e:v) { if (s) s = 0; else os << ", "; os << e; }
return os<<']';
}
template<class t,class u> ostream& operator<<(ostream& os,const map<t,u>& mp){
os<<'{'; int s = 1;
for(auto [x,y]:mp) { if (s) s = 0; else os << ", "; os<<x<<": "<<y; }
return os<<'}';
}

void sol() {
ll k;
string s;
cin >> s >> k;
int n = s.size();
string ans = "1"+string(n, '0');
vector<int> c(10);
string pre;
for (int i=0; i<n; i++) {
for (int j=9; j>s[i]-'0'; j--) {
auto t = c;
t[j] = 1;
int u = count(t.begin(), t.end(), 1);
if (u > k) continue;
int mn = 0;
if (u == k) {
while (t[mn] == 0) mn++;
}
string x = pre+char(j+'0')+string(n-i-1, char(mn+'0'));
// cout << x << endl;
ans = x;
}
pre.push_back(s[i]);
c[s[i]-'0'] = 1;
}
if (count(c.begin(), c.end(), 1) <= k) {
ans = s;
}
cout << ans << "\n";
}

int main() {
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifndef SINGLE_INPUT
int t;
cin >> t;
while (t--) {
sol();
}
#else
sol();
#endif
return 0;
}