B - Given Length and Sum of Digits... CodeForces - 489C (贪心)
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.
Input
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.
Output
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).
Examples
Input
2 15
Output
69 96
Input
3 0
Output
-1 -1
题意是:给出m,s。求出长度为m的数,各个位上的数加起来为s。求最小的和最大的数。
贪心的思想,对于最小的,从最右边开始,拿最大的往上怼,不能有前导零(而求最大时可以后面有零,这是区别)
对于最大的,从最左边开始,拿最大的往上怼,不用在乎后面为0,因为这样才能为最大。
对与输出为-1 -1 的情况,如果m*9<s,或者:s=0 时,只有m=1时有答案0,0。m>1时为-1 -1;
#include<iostream> #include<cstdio> using namespace std; typedef long long ll; ll a[105],b[105]; ll tot=0; int main() { ll m,s; while(cin>>m>>s) { if(m*9<s||(s<1&&m!=1)) cout<<"-1 -1"<<endl; else { int m1=m,s1=s; for(int i=m-1;i>=0;i--) { if(s>9) { a[i]=9; s-=9; } //还没到最后一位,尽量大得放 else if(i!=0) { a[i]=s-1; s=1; //这个是为了前一位尽量为1,因为此时已经小于9了;如果还没到第一位,而s=1,那么就上0; } else { a[i]=s;//到第一位了,那就没得分了,直接往上放。 } } //如果大于9,肯定往上放9。 for(int i=0;i<m1;i++) { if(s1>9) { b[i]=9; s1-=9; } else { b[i]=s1; s1=0; } } for(int i=0;i<m;i++) printf("%d",a[i]); printf(" "); for(int i=0;i<m;i++) printf("%d",b[i]); cout<<endl; } } }