Codeforces_B.Maximum Sum of Digits

 

http://codeforces.com/contest/1060/problem/B

 

题意:将n拆为a和b,让a+b=n且S(a)+S(b)最大,求最大的S(a)+S(b)。

思路:考虑任意一个数,例如156,将其分为 d1:(1,155)d2:(6,150),其实S(a)+S(b)都是12;但是当分为 d3:(7,149)d4:(9,147)时(此时,由d2变为d3,b的个位由0变为9,跨越0),S(a)+S(b)变为了21;将其分为 d5:(57,99)d6:(68,88)时,S(a)+S(b)变为30。S(a)+S(b)是如何变大的?考虑b任意一个数位,当其从0变为9,S(a)增大1,S(B)增大8;当是其它情况时(数位变化不跨越0),相当于S(a)+x, S(b)-x,S(a)+S(b)不变。总结起来,划分(a,b)时让尽量多的数位变化能够跨越0,等于让b的每一位尽量分最多出来。得到贪心策略,每一数位都分9出来。例如,对4394826划分为(999999,3394827)

 

#include<cstdio>
#include<iostream>
#include<cstring>

using namespace std;

#define LL long long

int digitsum(LL x)
{
    int res=0;
    while(x>0)
    {
        res+=x%10;
        x/=10;
    }
    return res;
}

int main()
{
    LL n;
    while(scanf("%I64d",&n)!=EOF)
    {
        int cnt9=0;
        LL tmp9=0;
        while(tmp9<=n)
        {
            tmp9=tmp9*10+9;
            cnt9++;
        }
        tmp9/=10;
        cnt9--;
        int res=cnt9*9+digitsum(n-tmp9);
        printf("%d\n",res);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/jasonlixuetao/p/9744406.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值