C.Given Length and Sum of Digits

本文介绍了一个算法问题,即给定一个正整数m和一个非负整数s,如何找出长度为m且各位数字之和为s的最小与最大非负十进制整数。文章探讨了实现这一目标的具体步骤,并提供了一段示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C.Given Length and Sum of Digits…

C.Given Length and Sum of Digits…

time limit per test: 1 second
每次测试的时间限制:1秒

memory limit per test: 256 megabytes
每次测试的内存限制:256兆字节

input: standard input
输入:标准输入

output: standard output
产出:标准产出

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和一个非负整数s。您的任务是找到具有长度的最小和最大的数字。

m and sum of digits s.The required numbers should be non-negative integers written in the decimal base without leading zeroes.
m and sum of digits s.The required numbers should be non-negative integers written in the decimal base without leading zeroes.

lnput
输入

The single line of the input contains a pair of integers m,s(1sm≤100,0≤s≤900)—the length and the sum of the digitsof the
The single line of the input contains a pair of integers m,s(1sm≤100,0≤s≤900)—the length and the sum of the digitsof the

required numbers.
required numbers.

output
输出量

ln the output print the pair of the required non-negative integer numbers— frst the minimum possible number, then— the maximum
ln the output print the pair of the required non-negative integer numbers— frst the minimum possible number, then— the maximum

possible number. f no numbers satisfying conditions required exist, print the pair of numbers “-1 -1”(without the quotes).
可能的号码。如果不存在满足所需条件的数字,则打印数字对“-1-1”(不带引号)。

最大数和最小数都需要使每个数尽量大(从前往后,从后往前),特判首位为

int a[101] = { 0 };
int main() {
    int  m, s,k=0;
    cin >> m >> s;
    if (s < 1 && m>1 || s > m * 9)
        cout << "-1 -1" << endl;
    else
    {
        for (; k < m; ++k)
        {
            if (s > 8)
                a[k] = 9, s -= 9;
            else
                k = s, s = 0;
        }
        sort(a, a + m);
        for (int i = 0; i < m; ++i)
            cout << a[i];
        cout << ' ';
        if (a[m - 1] == 0)
        {
            a[m - 1] = 0;
            for (int i = m - 2; m >= 0; --i)
                if (a[i] > 0)
                {
                    --a[i];
                    break;
                }
        }
        for (int i = m - 1; i >= 0; --i)
            cout << a[i];
        cout << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值