B. Maximize Sum of Digits
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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
用了二维数组存大数,结构体比较各个位的和以及大数。然而看同学的做法很简单,此题很水。
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; struct zz { int sum; __int64 num; }w[20]; bool f(zz x,zz y) { if(x.sum==y.sum) return x.num>y.num; else return x.sum>y.sum; } int main() { char n[111]; scanf("%s",n); int i,l,j; int a[111][20]; l=strlen(n); w[l-1].sum=0; w[l-1].num=0; for(j=0;j<l;j++) { a[l-1][j]=n[j]-'0'; w[l-1].sum+=a[l-1][j]; w[l-1].num=w[l-1].num*10+a[l-1][j]; } for(i=0;i<l-1;i++) { w[i].sum=0; w[i].num=0; for(j=0;j<l;j++) { if(i==j) { a[i][j]=n[j]-'0'-1; } else if(j<i) { a[i][j]=n[j]-'0'; } else { a[i][j]=9; } w[i].sum+=a[i][j]; w[i].num=w[i].num*10+a[i][j]; } } sort(w,w+l,f); printf("%I64d\n", w[0].num); return 0; }