C. Card Game

Topic: Example:

enter
4
4
-4 1 -3 5
4
1 -2 3 -4
3
-1 3 -5
1
-1

output
5
4
2
0

Idea:

        The meaning here is,

        When we take an odd number for i, we can get the value of the odd number i and remove the current card.

        When we get an even number for i, remove the current card.

        Here, after we remove the current card, the subscript i of the subsequent card will change, and the parity of the subsequent i will change.

        So when we start to fetch the numbers one by one from the back, we can cleverly avoid these changes, and then there will be greedy operations.

The code is explained in detail below:

#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#define endl '\n'
#define int long long
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define uset unordered_set
#pragma GCC optimize(3,"Ofast","inline")
#define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10;

inline void solve()
{	
	int n;
	cin >> n;

	umap<int,int>a;	// 存储卡牌数值

	for(int i = 1;i <= n;++i)
	{
		cin >> a[i];
	}

	// now 是取得的值多少
	int now = 0,ans = 0;

	// 开始贪心取值
	// 从后面开始取值,是因为当我们取一个 i 值后
	// 后面的 下标 i 就会变化,我们从后面 i 开始取值
	// 巧妙的避开这些变化
	for(int i = n;i > 0;--i)
	{
		// 当我们取得的 i 是偶数的时候
		if(i % 2 == 0)
		{
			// 更新我们的ans 
			ans = max(ans,now);
		}else
		{
			// 当我们取的 i 是奇数的时候,说明当前的 a[i] 也是可取的
			// 继续更新 ans
			ans = max(ans,a[i] + now);
		}
		
		// now 取值,我们只取 >= 0 更好的数值
		now += max(a[i],(int)0);
	}
	
	// 输出答案
	cout << ans << endl;
}

signed main()
{
//	freopen("a.txt", "r", stdin);
	___G;
	int _t = 1;
	cin >> _t;
	while (_t--)
	{
		solve();
	}
	return 0;
}

Last commit:

Guess you like

Origin blog.csdn.net/hacker_51/article/details/133363635