开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第10天,点击查看活动详情
【ICPC】2022西安站 J. Strange Sum | 贪心、签到
题目链接
题目
Given a sequence .
You are going to select zero or more elements of aa so that: if you select , then in any interval of length i (formally, in for any ) you can select at most 2 elements.
Calculate the maximal sum of the elements you select.
Input
The first line contains an integer ().
The second line contains integers ().
Output
Output a single integer denoting the answer.
题目大意
对于给定的长度为 的数组 , 从中选择若干个元素满足下述条件:
- 若选择了 ,则在 数组中任意长度为 的连续子数组中最多只能选择两个元素。即对于任意的 满足 ,原数组中任意长度为 的子段 中只能选择 2 个元素。
最大化选择的元素之和。
思路
赛中想了半天还试图反驳队友的正确思路QAQ,直到一看榜单过了 100+ 队伍才幡然悔悟……
如果我们选择的所有元素中,下标最大的那一个的下标是 ,则 中最多只能选择两个元素。
也就是说,也就是说我们最多只能选择两个元素。院题的题意可以直接等同于在整个数组中选择不超过两个元素,最大化他们的和。
又因为原数组中可能存在元素的值小于 0,所以我们先对给定的数组排序后,最终的答案就是 。
代码
#include <bits/stdc++.h>
using namespace std;
int a[100005];
int main(){
int n;
scanf("%d", &n);
for( int i = 1; i <= n; i++) scanf("%d", &a[i]);
sort(a +1, a + n + 1);
printf("%d", max({0, a[n], a[n] + a[n-1]}));
return 0;
}