CodeForces - 1060B F - Maximum Sum of Digits
阿新 • • 發佈:2018-11-09
題意:輸入C,找出A,B使得A,B的各個位數字和最大。
#include<cstdio> #include<cstdlib> #include<algorithm> #include<iostream> #include<math.h> #include<queue> #include<stack> #include<cstring> #include<string> //#include<map> typedef long long LL; using namespace std; int a, b, c; int fun(int num) { int add = 0; while (num > 0) { add += num % 10; num /= 10; } return add; } int main() { int NUM = 10; while (1) { int maxsum = 0, maxa, maxb; for (int i = 1; i < NUM/2; i++) { int j = NUM - i; if (fun(j) + fun(i) > maxsum) { maxsum = fun(j) + fun(i); maxa = i; maxb = j; } } cout << maxa <<" "<< maxb <<" "<< maxsum << endl; NUM++; } }
打表發現A和B其中一個數是由n個9組成的,所以只要找到小於C且由n個9組成的最大的數就行了。
#include<cstdio> #include<cstdlib> #include<algorithm> #include<iostream> #include<math.h> #include<queue> #include<stack> #include<cstring> #include<string> //#include<map> typedef long long LL; using namespace std; LL c, a, b; LL S(LL num) { int sum = 0; while (num>0) { sum += num % 10; num /= 10; } return sum; } int main() { cin >> c; if (c < 10) { cout << c; return 0; } a = 9; while (a < c) { a *= 10; a += 9; } a /= 10; b = c - a; cout << S(a) + S(b); }