Perfect Number 二分
Time limit:2000 ms Memory limit:262144 kB Source: Codeforces Round #460 (Div. 2) Tags: binary search brute force dp implementation number theory *1100 Editorial: Announcement Tutorial描述
We consider a positive integer perfect, if and only if the sum of its digits is exactly 10. Given a positive integer k, your task is to find the k-th smallest perfect positive integer.
输入
A single line with a positive integer k (1≤k≤10000).
输出
A single number, denoting the k-th smallest perfect integer.
Input
1
Output
19
Input
2
Output
28
提示
The first perfect integer is 19 and the second one is 28.
代码
#include<iostream>
#include<string.h>
#include<algorithm>
#include<stdio.h>
#include<queue>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> PII;
#define mod 1000000007
#define INF 0x3f3f3f3f
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
//head
int k;
int bit[11];//存放mid的各个元素
int dp[20][11];//表示到第i位,数位和为j的个数
int dfs(int pos, int sum, bool limit) {
if (pos == -1) return sum == 10;
if (sum > 10) return 0;
if (!limit&&dp[pos][sum] != -1) return dp[pos][sum];
int ans = 0;
int up = limit ? bit[pos] : 9;
for (int i = 0; i <= up; i++) {
ans += dfs(pos - 1, sum + i, limit && (i == up));
}
if (!limit) dp[pos][sum] = ans;
return ans;
}
int calc(int x) {
int len = 0;
while (x) {
bit[len++] = x % 10;
x /= 10;
}
return dfs(len - 1, 0, true);
}
int main() {
memset(dp, -1, sizeof(dp));
int lb = 0, ub = INF;
int ans = 0;
cin >> k;
while (ub - lb > 1) {
int mid = (lb + ub) / 2;
if (calc(mid) < k) lb = mid;//找到mid是第几个
else ans = mid, ub = mid;
}
printf("%d\n", ans);
return 0;
}
本人也是新手,也是在学习中,勿喷
转载请注明出处
欢迎有问题的小伙伴一起交流哦~