CF1343C
题目简化和分析:
给您一个序列,您要在其中选择若干个数使得:
- 相邻两数异号
- 长度最大,总和最大
我们可以牢牢抓住长度且总和最大,这一特性。
说明我们必须在每一个连续的同号的子串中被迫选择最大的,以满足这一属性。
例如,样例 \(1,2,3,-1,2\) 被我们分割成了 \(1,2,3\) 和 \(-1,-2\) 两个子串,为满足最大从中选择 \(3\) 和 \(-1\) 两个数。
本题涉及算法:贪心。
Solution:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
const int N=2e5+50;
const int M=1e5+50;
inline ll read(){
ll x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}
return x*f;
}
ll t,n;
ll a[N];
int main()
{
t=read();
while(t--){
n=read();
for(int i=1;i<=n;++i) a[i]=read();
ll l=a[1]>0?1:-1,ans=0,maxn=a[1];
for(int i=2;i<=n;++i){
ll res=a[i]>0?1:-1;
if(res==l) {
maxn=max(maxn,a[i]);
}else{
ans+=maxn;
maxn=a[i];
l=res;
}
}
ans+=maxn;
printf("%lld\n",ans);
}
return 0;
}

浙公网安备 33010602011771号