cf489c Given Length and Sum of Digits...

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值