1. 程式人生 > >CodeForces 1060 B Maximum Sum of Digits

CodeForces 1060 B Maximum Sum of Digits

Maximum Sum of Digits

  You are given a positive integer n.

  Let S(x)S(x) be sum of digits in base 10 representation of xx , for example, S(123)=1+2+3=6S(123)=1+2+3=6 , S(0)=0S(0)=0 .

  Your task is to find two integers a,ba,b , such that

0a,bn0≤a,b≤n , a+b=na+b=n and S(a)+S(b)S(a)+S(b) is the largest possible among all such pairs.

Input

  The only line of input contains an integer nn (1n1012)(1≤n≤1012) .

Output

  Print largest S(a)+S(b)S(a)+S(b) among all pairs of integers

a,b">a,ba,b , such that 0a,bn0≤a,b≤n and a+b=na+b=n .

Examples

Input
35
Output
17
Input
10000000000
Output
91

Note

  In the first example, you can choose, for example, a=17a=17 and b=18

b=18 , so that S(17)+S(18)=1+7+1+8=17S(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=5000000001a=5000000001 and b=4999999999b=4999999999 , with S(5000000001)+S(4999999999)=91S(5000000001)+S(4999999999)=91 . It can be shown that it is impossible to get a larger answer.

解題思路:
  給出一個數字n,將他拆分為2個數字,使拆分的兩個數字每一位相加的和最大,輸出相加後的和。

  個人感覺不用管下面提示。我們本著貪心的思想,希望獲得儘可能多的9,就是將35,拆分為9與26,將10000000000,拆分為9999999999與1,既將原始數字拆分為比其第一位的全由9組成的數字與另一個補償數字,補償數字為原始數字減去拆分的全9數字。之後將拆分的兩個數字所有位都相加便可以得到答案。

 1 #include<iostream>
 2 #include<sstream>
 3 #include<string>
 4 #include<cstdio>
 5 //CodeForces不支援萬能標頭檔案bits/stdc++.h
 6 using namespace std;
 7 typedef long long ll;
 8 string n;
 9 ll power(int a, int b){ //快速冪
10     ll ans = 1;
11     while(b){
12         if(b & 1){
13             ans = ans * a;
14         }
15         a = a * a;
16         b >>= 1;
17     }
18     return ans;
19 }
20 int main()
21 {
22     ll a, b;
23     while(cin >> n)
24     {
25         int suma=0;
26         int sumb=0;
27         a = power(10, n.size() - 1);
28         //若想拆分出小於且9最多的數字,只需要找到n的位數n.size() - 1
29         //之後便可以用10的n.size() - 1次冪找到與n位數相等數字中最小數字
30         //減一便可以得到我們所要拆分的數字
31         istringstream cinn(n);
32         cinn >> b;
33         //先用istringstream讀取n中的值輸入到整形b中
34         //b - a就是補償的數字。
35         a--;
36         b = b - a;
37         while(a)    //將a的每一位加起來
38         {
39             suma += a % 10;
40             a/=10;
41         }
42         while(b)
43         {
44             sumb += b % 10; //將b的每一位加起來
45             b/=10;
46         }
47         cout << suma + sumb << endl;    //所有位數加和
48     }
49     return 0;
50 }