B. Maximize Sum of Digits

Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits.

Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.

Input

The first line contains the positive integer x (1 ≤ x ≤ 1018) — the integer which Anton has.

Output

Print the positive integer which doesn't exceed x and has the maximum sum of digits. If there are several such integers, print the biggest of them. Printed integer must not contain leading zeros.

Examples
input
100
output
99
input
48
output
48
input
521
output
499


思路:1000+的人做出来,还以为多难,结果又是一个大水题。。。
题意是给定一个数n,求1—n之间的数的各项之和最大,若有多个最大值,挑数值最大的。
(翻译的心累)。。。我的做法是由数位DP的一点小东西改过来的,也就是通过改掉一个数
的其中某一项,得到一个上限,下面就可以全是9了,可以这么理解。。

代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<iostream>
#include<cmath>
using namespace std;
typedef long long LL;
int a[20];
void J_S(int &k,LL n)
{
    while(n)
    {
        a[k++]=n%10;
        n/=10;
    }
}
int main()
{
    LL n;
    while(~scanf("%I64d",&n))
    {
        memset(a,0,sizeof(a));
        int l=0;
        J_S(l,n);
        if(l==1)
            printf("%I64d\n",n);
        else
        {
            int x=l-1,pos=0,sum=0;
            int maxx=-1;
            for(int i=l-1; i>0; i--)
            {
                if(a[x]==0)
                {
                    x--;
                    continue;
                }
                for(int j=l-1; j>x; j--)
                    sum+=a[j];
                sum+=(a[x]-1+9*x);
                if(sum>=maxx)
                {
                    maxx=sum;
                    pos=x;
                }
                sum=0;
                x--;
            }
            int num=0;
            for(int i=0; i<l; i++)
                num+=a[i];
            if(num>=maxx)
                printf("%I64d\n",n);
            else
            {
                a[pos]-=1;
                for(int i=l-1; i>pos; i--)
                    printf("%d",a[i]);
                if(a[pos])
                    printf("%d",a[pos]);
                for(int i=pos-1; i>=0; i--)
                    printf("9");
                printf("\n");
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值