cf489c Given Length and Sum of Digits...
题目描述
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
题目大意:求长度为m,每一位数字的和s的最大数和最小数 1 ≤ m ≤ 100, 0 ≤ s ≤ 900
输入描述:
The single line of the input contains a pair of integers m, s (1 ≤ m ≤ 100, 0 ≤ s ≤ 900) — the length and the sum of the digits of the required numbers.
输出描述:
In the output print the pair of the required non-negative integer numbers — first the minimum possible number, then — the maximum possible number. If no numbers satisfying conditions required exist, print the pair of numbers "-1 -1" (without the quotes).
思路:
求最大值,从高位到低位尽量填大的
求最小值,对最大值反转,若第一位为0,则向最大值最后非0的那一位“借”个1。
注意:m*9<s、s<=0且m!=1时无解,还有s=0,m=1这个特例。
#include <iostream>
using namespace std;
int m, s;
int a[110]; //存放最大值每一位上的数字
int main() {
cin>>m>>s;
if ((s == 0 && m > 1) || s > 9*m) //如果m个9相加都比s小 或者 s小于等于0且m不为1 无解
{
cout<<"-1 -1";
return 0;
}
if (s == 0 && m == 1) //当s为0,且m为1,那么这个数就是0
{
cout<<"0 0";
return 0;
}
int pos = 0; //记录最大值中最后非0的数
for (int i = 1; i <= m; i++) //计算最大值
{
for (int j = 9; j>=1; j--)
{
if (s>=j)
{
a[i] = j;
pos = i;
s -= j;
break;
}
}
if (s == 0)
break;
}
int flag = 1; //判断最大值最后一位是否借过1
if (a[m] == 0) //若最大值最后一位为0,则向最后非0的那一位“借”1
{
a[m] = 1;
a[pos] -= 1;
flag = 0;
}
for (int i = m; i >= 1 ; i--) //最小值:反转最大值
{
cout<<a[i];
}
cout<<" ";
if (flag == 0) //若最小值借过1,则回调
{
a[m] = 0;
a[pos] += 1;
}
for (int i = 1; i <= m; i++) //最大值
{
cout<<a[i];
}
return 0;
}