CodeForces 489C (贪心) Given Length and Sum of Digits...
2014-11-18 13:40
459 查看
题意:
找出m位且各个数位数字之和为s的最大和最小整数,不包括前导0(比如说003是非法的),但0是可以的。
分析:
这题是用贪心来做的,同样是m位数,前面的数字越大这个数就越大。
所以写一个can(int m, int s)函数,来判断是否存在一个m位数其各位数字之和为s
这里先不考虑前导0的事,代码看起来可能是这个样子的:
比如我们现在要求满足要求的最小整数,从最左边的数开始从0到9开始试,如果后面的数能够构成m-1位和为s-d的数,就开始尝试下一位。
注意:在这里就要加上不能有前导0的判定条件。
求最大数也是类似的,而且还不用考虑前导0.
代码君
找出m位且各个数位数字之和为s的最大和最小整数,不包括前导0(比如说003是非法的),但0是可以的。
分析:
这题是用贪心来做的,同样是m位数,前面的数字越大这个数就越大。
所以写一个can(int m, int s)函数,来判断是否存在一个m位数其各位数字之和为s
这里先不考虑前导0的事,代码看起来可能是这个样子的:
bool can(int m, int s) { return (s >= 0 && s <= m*9); }
比如我们现在要求满足要求的最小整数,从最左边的数开始从0到9开始试,如果后面的数能够构成m-1位和为s-d的数,就开始尝试下一位。
注意:在这里就要加上不能有前导0的判定条件。
求最大数也是类似的,而且还不用考虑前导0.
#include <cstdio>
using namespace std;
const int maxn = 100 + 10;
char a[maxn], b[maxn];
bool can(int m, int s) { return (s >= 0 && s <= m*9); }
int main()
{
int m, s;
scanf("%d%d", &m, &s);
if(!can(m, s))
{
puts("-1 -1");
return 0;
}
int sum = s, p = 0;
for(int i = 0; i < m; ++i)
{
for(int d = 0; d < 10; ++d)
{
if((i > 0 || d > 0 || (m == 1 && d == 0)) && can(m-i-1, sum-d))
{
a[p++] = '0' + d;
sum -= d;
break;
}
}
}
if(p != m)
{
puts("-1 -1");
return 0;
}
for(int i = 0; i < p; ++i) putchar(a[i]);
putchar(' ');
sum = s; p = 0;
for(int i = 0; i < m; ++i)
{
for(int d = 9; d >= 0; --d)
{
if(can(m-i-1, sum-d))
{
b[p++] = '0' + d;
sum -= d;
break;
}
}
}
if(p != m)
{
puts("-1 -1");
return 0;
}
for(int i = 0; i < m; ++i) putchar(b[i]);
puts("");
return 0;
}
代码君
相关文章推荐
- Codeforces 489C - Given Length and Sum of Digits...(贪心)
- Codeforces-489C-Given Length and Sum of Digits...
- Codeforces #277.5 (Div. 2) C. Given Length and Sum of Digits...(简单贪心)
- Codeforces Round #277.5 (Div. 2)C. Given Length and Sum of Digits...(贪心)
- codeforces#277.5 C. Given Length and Sum of Digits
- Codeforces Round #277.5(Div. 2) C. Given Length and Sum of Digits...【贪心】
- Codeforces - 277.5 (Div. 2)C - Given Length and Sum of Digits...(模拟 or dfs)
- Codeforces Round #277.5 (Div. 2)——C贪心—— Given Length and Sum of Digits
- Codeforces Round #277.5 (Div. 2)C. Given Length and Sum of Digits...(贪心)
- codeforces#277.5 C. Given Length and Sum of Digits
- codeforces489 C. Given Length and Sum of Digits...【贪心】
- CF 489 C Given Length and Sum of Digits...(水题)
- Codeforces Round #277.5 (Div. 2) C. Given Length and Sum of Digits...
- Codeforces Round #277.5 (Div. 2)C——Given Length and Sum of Digits...
- 【寒江雪】C. Given Length and Sum of Digits
- Given Length and Sum of Digits...---------cf水题
- Codeforces Round #277.5 (Div. 2) C. Given Length and Sum of Digits...
- Codeforces Round #277.5 (Div. 2)C——Given Length and Sum of Digits...
- CF 277.5 C.Given Length and Sum of Digits.. 构造
- Codeforces Round #277.5 (Div. 2)-C. Given Length and Sum of Digits...