思想
就是用一个map,first存数值本身大小,second存数位和的值。
然后进行一个排序,如果数位和大小一致,那么就按数值本身大小升序排,否则就按照数位和大小升序排。
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 10;
int a[N];
int n, m;
map<int, int>mp;
struct CMP {
bool operator()(pair<int, int> &a, pair<int, int> &b) {
if (a.second == b.second)
return a.first < b.first;
return a.second < b.second;
}
};
int dismantle(int x) {
int sum = 0;
while (x) {
sum += x % 10;
x /= 10;
}
return sum;
}
void solve() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
a[i] = i;
//拆位求和
int t = dismantle(a[i]);
mp[a[i]] = t;
}
vector<pair<int, int>> v(mp.begin(), mp.end());
sort(v.begin(), v.end(), CMP());
cout << v[m].first << endl;
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
int t = 1;
while (t--)
solve();
return 0;
}
Debug:
修改了一下,输入时下标从1开始,输出时输出v[m-1].first就全部过了:
lambda式写法:
#include <bits/stdc++.h>
using namespace std;
int n, m;
int check(int x) { //计算数位之和
int count = 0;
while (x) {
count += x % 10;
x /= 10;
}
return count;
}
void solve() {
cin >> n >> m;
vector<int>a;
for (int i = 1; i <= n; i++) {
a.push_back(i);
}
//拆位求和
sort(a.begin(), a.end(), [](int x, int y) {
if (check(x) == check(y))
return x < y; //数位之和的按值大小排序
return check(x) < check(y); //按数位之和的大小排序
});
cout << a[m - 1] << endl;
}
int main() {
int t = 1;
while (t--)
solve();
return 0;
}