CodeForces - 1060B F - Maximum Sum of Digits

题目链接

题意:输入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);
}

猜你喜欢

转载自blog.csdn.net/leo_10/article/details/82971915