C. Card Game Codeforces Round 899 (Div. 2)

Problem - C - Codeforces

题目大意:有n张牌,每张牌上有一个数字a[i],每次操作可以选择一个奇数位置上的数,将其移除并获得上面的数,或者移除一个偶数位置上的数,每次移除后,所有数的位置都会对应紧凑,操作数量任意,问获得的数的和最大是多少

1<=n<=2e5;-1e9<=a[i]<=1e9

思路:可以发现,如果取了某个位置i上的数,那么它后面的数都可以任取,因为对于它后面任意一个位置j,如果j是奇数,就先取j,奇数位置上的数处理完后,再取i,然后后面原来是偶数的j都变成了奇数,这些j也都可以取了,这样就代表j都是任取的,只不过偶数位置上的数不能算在贡献里。

所以我们从后向前遍历,因为要求最大的和,所以我们只要正数,用sum维护当前后缀中所有正数的和,我们遍历到一个奇数位置时,因为她自身可以算贡献,答案就是a[i]+sum,如果是偶数位置,那么这个数只能扔掉,然后后面的的数可以任取,答案就是sum,对所有位置维护最大值即可

#include
//#include<__msvc_all_public_headers.hpp>
#include
using namespace std;
typedef long long ll;
const int N = 2e5 + 5;
ll n;
const ll MOD = 998244353;
ll a[N];
void init()
{
}
void solve()
{
	cin >> n;
	init();
	ll ans = 0, sum = 0;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
	}
	for (int i = n; i >= 1; i--)
	{
		if (i & 1)
		{
			ans = max(ans, a[i] + sum);//奇数位置当前数才有贡献,然后后面的数任取
		}
		else
		{
			ans = max(ans, sum);
		}
		sum += max(a[i], (ll)0);//求所有正数的和
	}
	cout << ans << endl;
}
int main()
{
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(false);
	int t;
	cin >> t;
	while (t--)
	{
		solve();
	}
	return 0;
}

你可能感兴趣的:(贪心,算法,c++)