Codeforces Round #636 C. Alternating Subsequence
Recall that the sequence bb is a a subsequence of the sequence aa if bb can be derived from aa by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1,2,1,3,1,2,1]a=[1,2,1,3,1,2,1] , then possible subsequences are: [1,1,1,1][1,1,1,1] , [3][3] and [1,2,1,3,1,2,1][1,2,1,3,1,2,1] , but not [3,2,3][3,2,3] and [1,1,1,1,2][1,1,1,1,2] .
You are given a sequence aa consisting of nn positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is kk then your task is to find the maximum sum of elements of some alternating subsequence of length kk .
You have to answer tt independent test cases.
The first line of the input contains one integer tt (1≤t≤1041≤t≤104 ) — the number of test cases. Then tt test cases follow.
The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105 ) — the number of elements in aa . The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109,ai≠0−109≤ai≤109,ai≠0 ), where aiai is the ii -th element of aa .
It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105 ).
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of aa .
4 5 1 2 3 -1 -2 4 -1 -2 -1 -3 10 -2 8 3 8 -4 -15 5 -2 -3 1 6 1 -1000000000 1 -1000000000 1 -1000000000
2 -1 6 -2999999997
猛一看似乎有点难,再一看发现就是把连续的同号的数看成一个块,把块内最大值累加到答案就行了,边读入边处理,数组都不用开0.0
#include <bits/stdc++.h> using namespace std; long long n,a[200005]; int main() { int t; cin>>t; while(t--) { cin>>n; long long i,pre,tempmax=-0x3f3f3f3f,ans=0; for(i=1;i<=n;i++) { scanf("%lld",&a[i]); if(i==1) { if(a[i]>0)pre=1; else pre=-1; tempmax=a[1]; } else { if(a[i]*pre<0)//换了块 { pre=-pre; ans+=tempmax; tempmax=a[i]; } else { tempmax=max(tempmax,a[i]); } } } ans+=tempmax;//最后一个块 cout<<ans<<endl; } return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!