1. 程式人生 > >1060B Maximum Sum of Digits (思維。)

1060B Maximum Sum of Digits (思維。)

B. Maximum Sum of Digits

You are given a positive integer n.

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

Your task is to find two integers a,b, such that 0≤a,b≤n, a+b=n and S(a)+S(b) is the largest possible among all such pairs.

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

Output Print largest S(a)+S(b) among all pairs of integers a,b, such that 0≤a,b≤n and a+b=n.

Examplesinput 35output 17

input 10000000000output 91

Note In the first example, you can choose, for example, a=17 and b=18, so that 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 and b=4999999999, with S(5000000001)+S(4999999999)=91. It can be shown that it is impossible to get a larger answer.

題意:告訴你 s(x) = x 這個數的各位位數之和。 如 s(123) = 1 + 2 + 3 = 6.  現在給你一個整數n, 要求你在 0 到 n  的範圍內找兩個數a 和 b 。是 a + b == n && s(a) + s(b) 最大;

思路:對於一個 數 x ,如果 x <= 18, 那麼 將 x 分成兩個數a, b  ..  s(a) + s(b) 就是等於 x 的。 所以我們可以對 一個數 x 的每一位進行計算,  如果當前位 是 9,那麼 ans += 9, 如果不是,就向前一位借 1, 然後 ans += 10 + 當前位。

AC程式碼:

#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define INT(t) int t; scanf("%d",&t)
#define LLI(t) LL t; scanf("%I64d",&t)

using namespace std;

int main()
{
    string n;
    while(cin >> n){
        int a[15] = {0};
        int p = 0;
        for(int i = 0;i < n.size();i ++)
            a[p ++] = n[i] - '0';

        LL ans = 0;
        for(int i = p - 1;i >= 0;i --){
            //debug(ans); debug(a[i]);
            if(a[i] < 0){
                a[i] += 10;
                a[i - 1] --;
            }
            if(a[i] == 9)
                ans += 9;
            else {
                if(i != 0){
                    ans += 10 + a[i];
                    a[i - 1] --;
                }
                else ans += a[i];
            }
        }
        printf("%I64d\n",ans);
    }
    return 0;
}