CodeForces - 797B. Odd sum

题目链接:http://codeforces.com/problemset/problem/797/B

题目大意:给你一个长度为n的整数序列,让你从中挑出一些数,使它们的和最大并且为奇数

数据范围:

1 ≤ n ≤ 1e5

-1e4 <= a[i] <= 1e4

解题思路:

嘿嘿,其实不是我自己的思路,后来我发现自己的想法太麻烦了。(orz CF红名dalao)

先判断每一个数,如果是奇数就存入vector,偶数就直接加到sum,然后降序排序,先加a[0]保证sum是奇数,后面每两个

在一起加一次,如果大于零就加到sum,小于零就直接可以break了。

从一到不难的题感受到了自己和大佬之间的差距

AC代码:

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;


int main(){
	int n;
	cin >> n;
	vector<int> a;
	int sum = 0;
	for(int i = 0; i < n; i++){
		int b;
		cin >> b;
		if(abs(b & 1))	a.push_back(b);
		else	sum += max(0, b);
	}
	sort(a.rbegin(), a.rend());
	sum += a[0];
	for(int i = 2; i < (int) a.size(); i += 2){
		if(a[i] + a[i - 1] > 0)		sum += a[i] + a[i - 1];
		else	break;
	}
	cout << sum << endl;
}





猜你喜欢

转载自blog.csdn.net/swunhj/article/details/79742722