题目
题意翻译
记 S(x)的各个数位之和
例如:S(123)=1+2+3=6,S(0)=0。
给定整数 n\ \left(1 \le n \le 10^{12}\right)n (1≤n≤10
12
) ,求一对自然数 a, b\ (0 \le a, b \le n)a,b (0≤a,b≤n),使得 S(a)+S(b)S(a)+S(b) 最大。输出这个最大值。
题目描述
You are given a positive integer n n .
Let S(x) S(x) be sum of digits in base 10 representation of x x , for example, S(123) = 1 + 2 + 3 = 6 S(123)=1+2+3=6 , S(0) = 0 S(0)=0 .
Your task is to find two integers a, b a,b , such that 0 \leq a, b \leq n 0≤a,b≤n , a + b = n a+b=n and S(a) + S(b) S(a)+S(b) is the largest possible among all such pairs.
输入输出格式
输入格式:
The only line of input contains an integer n n (1 \leq n \leq 10^{12}) (1≤n≤10
12
) .
输出格式:
Print largest S(a) + S(b) S(a)+S(b) among all pairs of integers a, b a,b , such that 0 \leq a, b \leq n 0≤a,b≤n and a + b = n a+b=n .
输入输出样例
输入样例#1: 复制
35
输出样例#1: 复制
17
输入样例#2: 复制
10000000000
输出样例#2: 复制
91
说明
In the first example, you can choose, for example, a = 17 a=17 and b = 18 b=18 , so that S(17) + S(18) = 1 + 7 + 1 + 8 = 17 S(17)+S(18)=1+7+1+8=17 . It can be shown that it is impossible to get a larger answer.
In the second test example, you can choose, for example, a = 5000000001 a=5000000001 and b = 4999999999 b=4999999999 , with S(5000000001) + S(4999999999) = 91 S(5000000001)+S(4999999999)=91 . It can be shown that it is impossible to get a larger answer.
思路
非常奇特!
一:找出S的位数CNT,A加上CNT-1位9;
比如S=2233213123的话,A一开始就等于999999999
二:A的第一位为S第一位数字-1
此时A就变成了1999999999
三:算出B=S-A,拆位,输出ans
(此时ans=109)
代码
#include<iostream>
using namespace std;
long long a=0,b,s,hk416,pow[15];
int fuze(long long a)
{
int cnt=0;
while(a)
{
cnt+=a%10;
a/=10;
}
cnt+=a;
return cnt;
}
int main()
{
pow[0]=1;
for(int i=1;i<=14;i++)
pow[i]=10*pow[i-1];
cin>>s;
hk416=s;
int cnt=0;
while(s/10)
{
a=a*10+9;
s/=10;
cnt++;
}
a+=(s-1)*pow[cnt];
b=hk416-a;
cout<<fuze(a)+fuze(b)<<endl;
return 0;
}