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