【CF1060B】Maximum Sum of Digits

题目

题意翻译
记 S(x)的各个数位之和
例如:S(123)=1+2+3=6,S(0)=0。

给定整数 n\ \left(1 \le n \le 10^{12}\right)n (1≤n≤10
12
) ,求一对自然数 a, b\ (0 \le a, b \le n)a,b (0≤a,b≤n),使得 S(a)+S(b)S(a)+S(b) 最大。输出这个最大值。

题目描述
You are given a positive integer n n .

Let S(x) S(x) be sum of digits in base 10 representation of x x , for example, S(123) = 1 + 2 + 3 = 6 S(123)=1+2+3=6 , S(0) = 0 S(0)=0 .

Your task is to find two integers a, b a,b , such that 0 \leq a, b \leq n 0≤a,b≤n , a + b = n a+b=n and S(a) + S(b) S(a)+S(b) is the largest possible among all such pairs.

输入输出格式
输入格式:
The only line of input contains an integer n n (1 \leq n \leq 10^{12}) (1≤n≤10
12
) .

输出格式:
Print largest S(a) + S(b) S(a)+S(b) among all pairs of integers a, b a,b , such that 0 \leq a, b \leq n 0≤a,b≤n and a + b = n a+b=n .

输入输出样例
输入样例#1: 复制
35
输出样例#1: 复制
17
输入样例#2: 复制
10000000000
输出样例#2: 复制
91
说明
In the first example, you can choose, for example, a = 17 a=17 and b = 18 b=18 , so that S(17) + S(18) = 1 + 7 + 1 + 8 = 17 S(17)+S(18)=1+7+1+8=17 . It can be shown that it is impossible to get a larger answer.

In the second test example, you can choose, for example, a = 5000000001 a=5000000001 and b = 4999999999 b=4999999999 , with S(5000000001) + S(4999999999) = 91 S(5000000001)+S(4999999999)=91 . It can be shown that it is impossible to get a larger answer.

思路

非常奇特!

一:找出S的位数CNT,A加上CNT-1位9;
比如S=2233213123的话,A一开始就等于999999999
二:A的第一位为S第一位数字-1
此时A就变成了1999999999
三:算出B=S-A,拆位,输出ans
(此时ans=109)

代码

#include<iostream>
using namespace std;
long long a=0,b,s,hk416,pow[15];
int fuze(long long a)

{
    int cnt=0;
    while(a)
    {
        cnt+=a%10;
        a/=10;
        }
    cnt+=a;
    return cnt;
}
int main()

{
    pow[0]=1;
    for(int i=1;i<=14;i++)
        pow[i]=10*pow[i-1];
    cin>>s;
    hk416=s;
    int cnt=0;
    while(s/10)
    {
        a=a*10+9;
        s/=10;
        cnt++;

        }

    a+=(s-1)*pow[cnt];
    b=hk416-a;

    cout<<fuze(a)+fuze(b)<<endl;
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值