AtCoder Grand Contest 021A - Digit Sum 2

A - Digit Sum 2


Time limit : 2sec / Memory limit : 256MB

Score : 300 points

Problem Statement

Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Constraints

  • 1N1016
  • N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.


Sample Input 1

Copy
100

Sample Output 1

Copy
18

For example, the sum of the digits in 99 is 18, which turns out to be the maximum value.


Sample Input 2

Copy
9995

Sample Output 2

Copy
35

For example, the sum of the digits in 9989 is 35, which turns out to be the maximum value.


Sample Input 3

Copy
3141592653589793

Sample Output 3

Copy
137

Submit

       在AtCoder上的第一场比赛,发篇文章感慨一下。

       有能力者可以阅读日文题解(我觉得日文题解比英文题解好懂)。

       与えられた数 N が 10 進法で K 桁からなるとします。最上位の桁が c であるとすれば、 N 以下の正の整
数は、

       • 下から K 桁目は c 以下

       • それ以外の位は 9 以下

       です。よって、答えは c + 9(K − 1) 以下となります。

       また、答えが c + 9(K − 1) のとき、条件を満たす整数は c999···999 のみです。この値が N 以下となるような N は c999···999 の形をしているものしかありえないため、この場合のみ答えが c + 9(K − 1) となります。

       そうでない場合、整数 (c − 1)999···999 は N 以下で、各桁の和は c + 9(K − 1) − 1 となります。よって
これが最適で、すべての場合について答えが求まりました。

       時間計算量は O(logN) です。

       第一题可以算数学思维题,我们发现只有a999···999这样的最后结果就是所以位相加,否则就是(a-1)999···999的所有位上数字之和最大。应该显而易见。好了,发现了这一点就非常简单写出代码就可以了。

Code:

#include
#include
#include
#include
#include
#include
#define ll long long 
using namespace std;
inline int read()
{
	int x=0,f=1;char s=getchar();
	while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
	while(s<='9'&&s>='0'){x=x*10+s-'0';s=getchar();}
	return x*f;
}
int main()
{
	char ch[50];
	scanf("%s",ch);
	bool flag=true;
	for(int i=1;i

你可能感兴趣的:(#,基本数论(数学),Atcoder)